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-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,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,71 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.io.IOException;
/**
* Interface used for {@link org.springframework.beans.TestBean}.
*
* <p>Two methods are the same as on Person, but if this
* extends person it breaks quite a few tests..
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public interface ITestBean {
int getAge();
void setAge(int age);
String getName();
void setName(String name);
ITestBean getSpouse();
void setSpouse(ITestBean spouse);
ITestBean[] getSpouses();
String[] getStringArray();
void setStringArray(String[] stringArray);
/**
* Throws a given (non-null) exception.
*/
void exceptional(Throwable t) throws Throwable;
Object returnsThis();
INestedTestBean getDoctor();
INestedTestBean getLawyer();
IndexedTestBean getNestedIndexedBean();
/**
* Increment the age by one.
* @return the previous age
*/
int haveBirthday();
void unreliableFileOperation() throws IOException;
}

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,437 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.util.ObjectUtils;
/**
* Simple test bean used for testing bean factories, the AOP framework etc.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 15 April 2001
*/
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
private String beanName;
private String country;
private BeanFactory beanFactory;
private boolean postProcessed;
private String name;
private String sex;
private int age;
private boolean jedi;
private ITestBean[] spouses;
private String touchy;
private String[] stringArray;
private Integer[] someIntegerArray;
private Date date = new Date();
private Float myFloat = new Float(0.0);
private Collection friends = new LinkedList();
private Set someSet = new HashSet();
private Map someMap = new HashMap();
private List someList = new ArrayList();
private Properties someProperties = new Properties();
private INestedTestBean doctor = new NestedTestBean();
private INestedTestBean lawyer = new NestedTestBean();
private IndexedTestBean nestedIndexedBean;
private boolean destroyed;
private Number someNumber;
private Colour favouriteColour;
private Boolean someBoolean;
private List otherColours;
private List pets;
public TestBean() {
}
public TestBean(String name) {
this.name = name;
}
public TestBean(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public TestBean(String name, int age) {
this.name = name;
this.age = age;
}
public TestBean(ITestBean spouse, Properties someProperties) {
this.spouses = new ITestBean[] {spouse};
this.someProperties = someProperties;
}
public TestBean(List someList) {
this.someList = someList;
}
public TestBean(Set someSet) {
this.someSet = someSet;
}
public TestBean(Map someMap) {
this.someMap = someMap;
}
public TestBean(Properties someProperties) {
this.someProperties = someProperties;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
public BeanFactory getBeanFactory() {
return beanFactory;
}
public void setPostProcessed(boolean postProcessed) {
this.postProcessed = postProcessed;
}
public boolean isPostProcessed() {
return postProcessed;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
if (this.name == null) {
this.name = sex;
}
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean isJedi() {
return jedi;
}
public void setJedi(boolean jedi) {
this.jedi = jedi;
}
public ITestBean getSpouse() {
return (spouses != null ? spouses[0] : null);
}
public void setSpouse(ITestBean spouse) {
this.spouses = new ITestBean[] {spouse};
}
public ITestBean[] getSpouses() {
return spouses;
}
public String getTouchy() {
return touchy;
}
public void setTouchy(String touchy) throws Exception {
if (touchy.indexOf('.') != -1) {
throw new Exception("Can't contain a .");
}
if (touchy.indexOf(',') != -1) {
throw new NumberFormatException("Number format exception: contains a ,");
}
this.touchy = touchy;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String[] getStringArray() {
return stringArray;
}
public void setStringArray(String[] stringArray) {
this.stringArray = stringArray;
}
public Integer[] getSomeIntegerArray() {
return someIntegerArray;
}
public void setSomeIntegerArray(Integer[] someIntegerArray) {
this.someIntegerArray = someIntegerArray;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Float getMyFloat() {
return myFloat;
}
public void setMyFloat(Float myFloat) {
this.myFloat = myFloat;
}
public Collection getFriends() {
return friends;
}
public void setFriends(Collection friends) {
this.friends = friends;
}
public Set getSomeSet() {
return someSet;
}
public void setSomeSet(Set someSet) {
this.someSet = someSet;
}
public Map getSomeMap() {
return someMap;
}
public void setSomeMap(Map someMap) {
this.someMap = someMap;
}
public List getSomeList() {
return someList;
}
public void setSomeList(List someList) {
this.someList = someList;
}
public Properties getSomeProperties() {
return someProperties;
}
public void setSomeProperties(Properties someProperties) {
this.someProperties = someProperties;
}
public INestedTestBean getDoctor() {
return doctor;
}
public void setDoctor(INestedTestBean doctor) {
this.doctor = doctor;
}
public INestedTestBean getLawyer() {
return lawyer;
}
public void setLawyer(INestedTestBean lawyer) {
this.lawyer = lawyer;
}
public Number getSomeNumber() {
return someNumber;
}
public void setSomeNumber(Number someNumber) {
this.someNumber = someNumber;
}
public Colour getFavouriteColour() {
return favouriteColour;
}
public void setFavouriteColour(Colour favouriteColour) {
this.favouriteColour = favouriteColour;
}
public Boolean getSomeBoolean() {
return someBoolean;
}
public void setSomeBoolean(Boolean someBoolean) {
this.someBoolean = someBoolean;
}
public IndexedTestBean getNestedIndexedBean() {
return nestedIndexedBean;
}
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
this.nestedIndexedBean = nestedIndexedBean;
}
public List getOtherColours() {
return otherColours;
}
public void setOtherColours(List otherColours) {
this.otherColours = otherColours;
}
public List getPets() {
return pets;
}
public void setPets(List pets) {
this.pets = pets;
}
/**
* @see org.springframework.beans.ITestBean#exceptional(Throwable)
*/
public void exceptional(Throwable t) throws Throwable {
if (t != null) {
throw t;
}
}
public void unreliableFileOperation() throws IOException {
throw new IOException();
}
/**
* @see org.springframework.beans.ITestBean#returnsThis()
*/
public Object returnsThis() {
return this;
}
/**
* @see org.springframework.beans.IOther#absquatulate()
*/
public void absquatulate() {
}
public int haveBirthday() {
return age++;
}
public void destroy() {
this.destroyed = true;
}
public boolean wasDestroyed() {
return destroyed;
}
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null || !(other instanceof TestBean)) {
return false;
}
TestBean tb2 = (TestBean) other;
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
}
public int hashCode() {
return this.age;
}
public int compareTo(Object other) {
if (this.name != null && other instanceof TestBean) {
return this.name.compareTo(((TestBean) other).getName());
}
else {
return 1;
}
}
public String toString() {
return this.name;
}
}

View File

@@ -0,0 +1,329 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import java.beans.PropertyEditorSupport;
import java.util.StringTokenizer;
import junit.framework.TestCase;
import junit.framework.Assert;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyBatchUpdateException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
/**
* Subclasses must implement setUp() to initialize bean factory
* and any other variables they need.
*
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractBeanFactoryTests extends TestCase {
protected abstract BeanFactory getBeanFactory();
/**
* Roderick beans inherits from rod, overriding name only.
*/
public void testInheritance() {
assertTrue(getBeanFactory().containsBean("rod"));
assertTrue(getBeanFactory().containsBean("roderick"));
TestBean rod = (TestBean) getBeanFactory().getBean("rod");
TestBean roderick = (TestBean) getBeanFactory().getBean("roderick");
assertTrue("not == ", rod != roderick);
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
assertTrue("rod.age is 31", rod.getAge() == 31);
assertTrue("roderick.name is Roderick", roderick.getName().equals("Roderick"));
assertTrue("roderick.age was inherited", roderick.getAge() == rod.getAge());
}
public void testGetBeanWithNullArg() {
try {
getBeanFactory().getBean((String) null);
fail("Can't get null bean");
}
catch (IllegalArgumentException ex) {
// OK
}
}
/**
* Test that InitializingBean objects receive the afterPropertiesSet() callback
*/
public void testInitializingBeanCallback() {
MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized");
// The dummy business method will throw an exception if the
// afterPropertiesSet() callback wasn't invoked
mbi.businessMethod();
}
/**
* Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the
* afterPropertiesSet() callback before BeanFactoryAware callbacks
*/
public void testLifecycleCallbacks() {
LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle");
Assert.assertEquals("lifecycle", lb.getBeanName());
// The dummy business method will throw an exception if the
// necessary callbacks weren't invoked in the right order.
lb.businessMethod();
assertTrue("Not destroyed", !lb.isDestroyed());
}
public void testFindsValidInstance() {
try {
Object o = getBeanFactory().getBean("rod");
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
TestBean rod = (TestBean) o;
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
assertTrue("rod.age is 31", rod.getAge() == 31);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testGetInstanceByMatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance with matching class");
}
}
public void testGetInstanceByNonmatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testGetSharedInstanceByMatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance with matching class");
}
}
public void testGetSharedInstanceByMatchingClassNoCatch() {
Object o = getBeanFactory().getBean("rod", TestBean.class);
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
}
public void testGetSharedInstanceByNonmatchingClass() {
try {
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
}
catch (BeanNotOfRequiredTypeException ex) {
// So far, so good
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testSharedInstancesAreEqual() {
try {
Object o = getBeanFactory().getBean("rod");
assertTrue("Rod bean1 is a TestBean", o instanceof TestBean);
Object o1 = getBeanFactory().getBean("rod");
assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean);
assertTrue("Object equals applies", o == o1);
}
catch (Exception ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on getting valid instance");
}
}
public void testPrototypeInstancesAreIndependent() {
TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy");
TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy");
assertTrue("ref equal DOES NOT apply", tb1 != tb2);
assertTrue("object equal true", tb1.equals(tb2));
tb1.setAge(1);
tb2.setAge(2);
assertTrue("1 age independent = 1", tb1.getAge() == 1);
assertTrue("2 age independent = 2", tb2.getAge() == 2);
assertTrue("object equal now false", !tb1.equals(tb2));
}
public void testNotThere() {
assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
try {
Object o = getBeanFactory().getBean("Mr Squiggle");
fail("Can't find missing bean");
}
catch (BeansException ex) {
//ex.printStackTrace();
//fail("Shouldn't throw exception on getting valid instance");
}
}
public void testValidEmpty() {
try {
Object o = getBeanFactory().getBean("validEmpty");
assertTrue("validEmpty bean is a TestBean", o instanceof TestBean);
TestBean ve = (TestBean) o;
assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null);
}
catch (BeansException ex) {
ex.printStackTrace();
fail("Shouldn't throw exception on valid empty");
}
}
public void xtestTypeMismatch() {
try {
Object o = getBeanFactory().getBean("typeMismatch");
fail("Shouldn't succeed with type mismatch");
}
catch (BeanCreationException wex) {
assertEquals("typeMismatch", wex.getBeanName());
assertTrue(wex.getCause() instanceof PropertyBatchUpdateException);
PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause();
// Further tests
assertTrue("Has one error ", ex.getExceptionCount() == 1);
assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
}
}
public void testGrandparentDefinitionFoundInBeanFactory() throws Exception {
TestBean dad = (TestBean) getBeanFactory().getBean("father");
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testFactorySingleton() throws Exception {
assertTrue(getBeanFactory().isSingleton("&singletonFactory"));
assertTrue(getBeanFactory().isSingleton("singletonFactory"));
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME));
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory");
assertTrue("Singleton references ==", tb == tb2);
assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null);
}
public void testFactoryPrototype() throws Exception {
assertTrue(getBeanFactory().isSingleton("&prototypeFactory"));
assertFalse(getBeanFactory().isSingleton("prototypeFactory"));
TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory");
assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME));
TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory");
assertTrue("Prototype references !=", tb != tb2);
}
/**
* Check that we can get the factory bean itself.
* This is only possible if we're dealing with a factory
* @throws Exception
*/
public void testGetFactoryItself() throws Exception {
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
assertTrue(factory != null);
}
/**
* Check that afterPropertiesSet gets called on factory
* @throws Exception
*/
public void testFactoryIsInitialized() throws Exception {
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized());
}
/**
* It should be illegal to dereference a normal bean
* as a factory
*/
public void testRejectsFactoryGetOnNormalBean() {
try {
getBeanFactory().getBean("&rod");
fail("Shouldn't permit factory get on normal bean");
}
catch (BeanIsNotAFactoryException ex) {
// Ok
}
}
// TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
// and rename this class
public void testAliasing() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ConfigurableBeanFactory)) {
return;
}
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;
String alias = "rods alias";
try {
cbf.getBean(alias);
fail("Shouldn't permit factory get on normal bean");
}
catch (NoSuchBeanDefinitionException ex) {
// Ok
assertTrue(alias.equals(ex.getBeanName()));
}
// Create alias
cbf.registerAlias("rod", alias);
Object rod = getBeanFactory().getBean("rod");
Object aliasRod = getBeanFactory().getBean(alias);
assertTrue(rod == aliasRod);
}
public static class TestBeanEditor extends PropertyEditorSupport {
public void setAsText(String text) {
TestBean tb = new TestBean();
StringTokenizer st = new StringTokenizer(text, "_");
tb.setName(st.nextToken());
tb.setAge(Integer.parseInt(st.nextToken()));
setValue(tb);
}
}
}

View File

@@ -0,0 +1,86 @@
/*
* 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 junit.framework.Assert;
import org.springframework.beans.TestBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests {
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ListableBeanFactory)) {
throw new IllegalStateException("ListableBeanFactory required");
}
return (ListableBeanFactory) bf;
}
/**
* Subclasses can override this.
*/
public void testCount() {
assertCount(13);
}
protected final void assertCount(int count) {
String[] defnames = getListableBeanFactory().getBeanDefinitionNames();
Assert.assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count);
}
public void assertTestBeanCount(int count) {
String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false);
Assert.assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " +
defNames.length, defNames.length == count);
int countIncludingFactoryBeans = count + 2;
String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true);
Assert.assertTrue("We should have " + countIncludingFactoryBeans +
" beans for class org.springframework.beans.TestBean, not " + names.length,
names.length == countIncludingFactoryBeans);
}
public void testGetDefinitionsForNoSuchClass() {
String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class);
Assert.assertTrue("No string definitions", defnames.length == 0);
}
/**
* Check that count refers to factory class, not bean class. (We don't know
* what type factories may return, and it may even change over time.)
*/
public void testGetCountForFactoryClass() {
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
}
public void testContainsBeanDefinition() {
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("rod"));
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("roderick"));
}
}

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,158 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
/**
* Simple test of BeanFactory initialization and lifecycle callbacks.
*
* @author Rod Johnson
* @author Colin Sampaleanu
* @since 12.03.2003
*/
public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
protected boolean initMethodDeclared = false;
protected String beanName;
protected BeanFactory owningFactory;
protected boolean postProcessedBeforeInit;
protected boolean inited;
protected boolean initedViaDeclaredInitMethod;
protected boolean postProcessedAfterInit;
protected boolean destroyed;
public void setInitMethodDeclared(boolean initMethodDeclared) {
this.initMethodDeclared = initMethodDeclared;
}
public boolean isInitMethodDeclared() {
return initMethodDeclared;
}
public void setBeanName(String name) {
this.beanName = name;
}
public String getBeanName() {
return beanName;
}
public void setBeanFactory(BeanFactory beanFactory) {
this.owningFactory = beanFactory;
}
public void postProcessBeforeInit() {
if (this.inited || this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet");
}
if (this.postProcessedBeforeInit) {
throw new RuntimeException("Factory called postProcessBeforeInit twice");
}
this.postProcessedBeforeInit = true;
}
public void afterPropertiesSet() {
if (this.owningFactory == null) {
throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean");
}
if (!this.postProcessedBeforeInit) {
throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet");
}
if (this.inited) {
throw new RuntimeException("Factory called afterPropertiesSet twice");
}
this.inited = true;
}
public void declaredInitMethod() {
if (!this.inited) {
throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method");
}
if (this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called declared init method twice");
}
this.initedViaDeclaredInitMethod = true;
}
public void postProcessAfterInit() {
if (!this.inited) {
throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet");
}
if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) {
throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method");
}
if (this.postProcessedAfterInit) {
throw new RuntimeException("Factory called postProcessAfterInit twice");
}
this.postProcessedAfterInit = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) ||
!this.postProcessedAfterInit) {
throw new RuntimeException("Factory didn't initialize lifecycle object correctly");
}
}
public void destroy() {
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
this.destroyed = true;
}
public boolean isDestroyed() {
return destroyed;
}
public static class PostProcessor implements BeanPostProcessor {
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessBeforeInit();
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
if (bean instanceof LifecycleBean) {
((LifecycleBean) bean).postProcessAfterInit();
}
return bean;
}
}
}

View File

@@ -0,0 +1,46 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import org.springframework.beans.factory.InitializingBean;
/**
* Simple test of BeanFactory initialization
* @author Rod Johnson
* @since 12.03.2003
*/
public class MustBeInitialized implements InitializingBean {
private boolean inited;
/**
* @see InitializingBean#afterPropertiesSet()
*/
public void afterPropertiesSet() throws Exception {
this.inited = true;
}
/**
* Dummy business method that will fail unless the factory
* managed the bean's lifecycle correctly
*/
public void businessMethod() {
if (!this.inited)
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Locale;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationContextException;
import org.springframework.context.NoSuchMessageException;
public class ACATester implements ApplicationContextAware {
private ApplicationContext ac;
public void setApplicationContext(ApplicationContext ctx) throws ApplicationContextException {
// check reinitialization
if (this.ac != null) {
throw new IllegalStateException("Already initialized");
}
// check message source availability
if (ctx != null) {
try {
ctx.getMessage("code1", null, Locale.getDefault());
}
catch (NoSuchMessageException ex) {
// expected
}
}
this.ac = ctx;
}
public ApplicationContext getApplicationContext() {
return ac;
}
}

View File

@@ -0,0 +1,157 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Locale;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.AbstractListableBeanFactoryTests;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.LifecycleBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractApplicationContextTests extends AbstractListableBeanFactoryTests {
/** Must be supplied as XML */
public static final String TEST_NAMESPACE = "testNamespace";
protected ConfigurableApplicationContext applicationContext;
/** Subclass must register this */
protected TestListener listener = new TestListener();
protected TestListener parentListener = new TestListener();
protected void setUp() throws Exception {
this.applicationContext = createContext();
}
protected BeanFactory getBeanFactory() {
return applicationContext;
}
protected ApplicationContext getApplicationContext() {
return applicationContext;
}
/**
* Must register a TestListener.
* Must register standard beans.
* Parent must register rod with name Roderick
* and father with name Albert.
*/
protected abstract ConfigurableApplicationContext createContext() throws Exception;
public void testContextAwareSingletonWasCalledBack() throws Exception {
ACATester aca = (ACATester) applicationContext.getBean("aca");
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
Object aca2 = applicationContext.getBean("aca");
assertTrue("Same instance", aca == aca2);
assertTrue("Says is singleton", applicationContext.isSingleton("aca"));
}
public void testContextAwarePrototypeWasCalledBack() throws Exception {
ACATester aca = (ACATester) applicationContext.getBean("aca-prototype");
assertTrue("has had context set", aca.getApplicationContext() == applicationContext);
Object aca2 = applicationContext.getBean("aca-prototype");
assertTrue("NOT Same instance", aca != aca2);
assertTrue("Says is prototype", !applicationContext.isSingleton("aca-prototype"));
}
public void testParentNonNull() {
assertTrue("parent isn't null", applicationContext.getParent() != null);
}
public void testGrandparentNull() {
assertTrue("grandparent is null", applicationContext.getParent().getParent() == null);
}
public void testOverrideWorked() throws Exception {
TestBean rod = (TestBean) applicationContext.getParent().getBean("rod");
assertTrue("Parent's name differs", rod.getName().equals("Roderick"));
}
public void testGrandparentDefinitionFound() throws Exception {
TestBean dad = (TestBean) applicationContext.getBean("father");
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testGrandparentTypedDefinitionFound() throws Exception {
TestBean dad = (TestBean) applicationContext.getBean("father", TestBean.class);
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
}
public void testCloseTriggersDestroy() {
LifecycleBean lb = (LifecycleBean) applicationContext.getBean("lifecycle");
assertTrue("Not destroyed", !lb.isDestroyed());
applicationContext.close();
if (applicationContext.getParent() != null) {
((ConfigurableApplicationContext) applicationContext.getParent()).close();
}
assertTrue("Destroyed", lb.isDestroyed());
applicationContext.close();
if (applicationContext.getParent() != null) {
((ConfigurableApplicationContext) applicationContext.getParent()).close();
}
assertTrue("Destroyed", lb.isDestroyed());
}
public void testMessageSource() throws NoSuchMessageException {
assertEquals("message1", applicationContext.getMessage("code1", null, Locale.getDefault()));
assertEquals("message2", applicationContext.getMessage("code2", null, Locale.getDefault()));
try {
applicationContext.getMessage("code0", null, Locale.getDefault());
fail("looking for code0 should throw a NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// that's how it should be
}
}
public void testEvents() throws Exception {
listener.zeroCounter();
parentListener.zeroCounter();
assertTrue("0 events before publication", listener.getEventCount() == 0);
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
}
public void testBeanAutomaticallyHearsEvents() throws Exception {
//String[] listenerNames = ((ListableBeanFactory) applicationContext).getBeanDefinitionNames(ApplicationListener.class);
//assertTrue("listeners include beanThatListens", Arrays.asList(listenerNames).contains("beanThatListens"));
BeanThatListens b = (BeanThatListens) applicationContext.getBean("beanThatListens");
b.zero();
assertTrue("0 events before publication", b.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + b.getEventCount(), b.getEventCount() == 1);
}
public static class MyEvent extends ApplicationEvent {
public MyEvent(Object source) {
super(source);
}
}
}

View File

@@ -0,0 +1,39 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* @author Juergen Hoeller
*/
public class BeanThatBroadcasts implements ApplicationContextAware {
public ApplicationContext applicationContext;
public int receivedCount;
public void setApplicationContext(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
if (applicationContext.getDisplayName().indexOf("listener") != -1) {
applicationContext.getBean("listener");
}
}
}

View File

@@ -0,0 +1,61 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.context;
import java.util.Map;
/**
* A stub {@link ApplicationListener}.
*
* @author Thomas Risberg
* @author Juergen Hoeller
*/
public class BeanThatListens implements ApplicationListener {
private BeanThatBroadcasts beanThatBroadcasts;
private int eventCount;
public BeanThatListens() {
}
public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) {
this.beanThatBroadcasts = beanThatBroadcasts;
Map beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class);
if (!beans.isEmpty()) {
throw new IllegalStateException("Shouldn't have found any BeanThatListens instances");
}
}
public void onApplicationEvent(ApplicationEvent event) {
eventCount++;
if (beanThatBroadcasts != null) {
beanThatBroadcasts.receivedCount++;
}
}
public int getEventCount() {
return eventCount;
}
public void zero() {
eventCount = 0;
}
}

View File

@@ -0,0 +1,37 @@
package org.springframework.context;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.LifecycleBean;
/**
* Simple bean to test ApplicationContext lifecycle methods for beans
*
* @author Colin Sampaleanu
* @since 03.07.2004
*/
public class LifecycleContextBean extends LifecycleBean implements ApplicationContextAware {
protected ApplicationContext owningContext;
public void setBeanFactory(BeanFactory beanFactory) {
super.setBeanFactory(beanFactory);
if (this.owningContext != null)
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
}
public void afterPropertiesSet() {
super.afterPropertiesSet();
if (this.owningContext == null)
throw new RuntimeException("Factory didn't call setAppliationContext before afterPropertiesSet on lifecycle bean");
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (this.owningFactory == null)
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
this.owningContext = applicationContext;
}
}

View File

@@ -0,0 +1,28 @@
package org.springframework.context;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
/**
* Listener that maintains a global count of events.
*
* @author Rod Johnson
* @since January 21, 2001
*/
public class TestListener implements ApplicationListener {
private int eventCount;
public int getEventCount() {
return eventCount;
}
public void zeroCounter() {
eventCount = 0;
}
public void onApplicationEvent(ApplicationEvent e) {
++eventCount;
}
}

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 org.springframework.mock.web.MockServletContext}.
* @see org.springframework.mock.web.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,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,352 @@
/*
* 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.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.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.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletContext;
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).
*
* @author Rod Johnson
* @author Juergen Hoeller
* @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 final Map<String, ServletContext> contexts = new HashMap<String, ServletContext>();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private String servletContextName = "MockServletContext";
/**
* Create a new MockServletContext, using no base path and a
* DefaultResourceLoader (i.e. the classpath root as WAR root).
* @see org.springframework.core.io.DefaultResourceLoader
*/
public MockServletContext() {
this("", null);
}
/**
* Create a new MockServletContext, using a DefaultResourceLoader.
* @param resourceBasePath the WAR root directory (should not end with a slash)
* @see org.springframework.core.io.DefaultResourceLoader
*/
public MockServletContext(String resourceBasePath) {
this(resourceBasePath, null);
}
/**
* Create a new MockServletContext, using the specified ResourceLoader
* and no base path.
* @param resourceLoader the ResourceLoader to use (or null for the default)
*/
public MockServletContext(ResourceLoader resourceLoader) {
this("", resourceLoader);
}
/**
* Create a new MockServletContext.
* @param resourceBasePath the WAR root directory (should not end with a slash)
* @param resourceLoader the ResourceLoader to use (or null for the default)
*/
public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader) {
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
// Use JVM temp dir as ServletContext temp dir.
String tempDir = System.getProperty(TEMP_DIR_SYSTEM_PROPERTY);
if (tempDir != null) {
this.attributes.put(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, new File(tempDir));
}
}
/**
* Build a full resource location for the given path,
* prepending the resource base path of this MockServletContext.
* @param path the path as specified
* @return the full resource path
*/
protected String getResourceLocation(String path) {
if (!path.startsWith("/")) {
path = "/" + path;
}
return this.resourceBasePath + path;
}
public void setContextPath(String contextPath) {
this.contextPath = (contextPath != null ? contextPath : "");
}
/* This is a Servlet API 2.5 method. */
public String getContextPath() {
return this.contextPath;
}
public void registerContext(String contextPath, ServletContext context) {
this.contexts.put(contextPath, context);
}
public ServletContext getContext(String contextPath) {
if (this.contextPath.equals(contextPath)) {
return this;
}
return this.contexts.get(contextPath);
}
public int getMajorVersion() {
return 2;
}
public int getMinorVersion() {
return 5;
}
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) {
return null;
}
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);
}
}
}

View File

@@ -0,0 +1,86 @@
/*
* 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.portlet;
import javax.portlet.ActionRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
/**
* Mock implementation of the {@link javax.portlet.ActionRequest} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockActionRequest extends MockClientDataRequest implements ActionRequest {
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public MockActionRequest() {
super();
}
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param actionName the name of the action to trigger
*/
public MockActionRequest(String actionName) {
super();
setParameter(ActionRequest.ACTION_NAME, actionName);
}
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param portletMode the mode that the portlet runs in
*/
public MockActionRequest(PortletMode portletMode) {
super();
setPortletMode(portletMode);
}
/**
* Create a new MockActionRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
*/
public MockActionRequest(PortletContext portletContext) {
super(portletContext);
}
/**
* Create a new MockActionRequest.
* @param portalContext the PortalContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockActionRequest(PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
}
@Override
protected String getLifecyclePhase() {
return ACTION_PHASE;
}
}

View File

@@ -0,0 +1,122 @@
/*
* 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.portlet;
import java.io.IOException;
import java.util.Map;
import javax.portlet.ActionResponse;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.portlet.ActionResponse} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockActionResponse extends MockStateAwareResponse implements ActionResponse {
private boolean redirectAllowed = true;
private String redirectedUrl;
/**
* Create a new MockActionResponse with a default {@link MockPortalContext}.
* @see MockPortalContext
*/
public MockActionResponse() {
super();
}
/**
* Create a new MockActionResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockActionResponse(PortalContext portalContext) {
super(portalContext);
}
public void setWindowState(WindowState windowState) throws WindowStateException {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set WindowState after sendRedirect has been called");
}
super.setWindowState(windowState);
this.redirectAllowed = false;
}
public void setPortletMode(PortletMode portletMode) throws PortletModeException {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set PortletMode after sendRedirect has been called");
}
super.setPortletMode(portletMode);
this.redirectAllowed = false;
}
public void setRenderParameters(Map<String, String[]> parameters) {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called");
}
super.setRenderParameters(parameters);
this.redirectAllowed = false;
}
public void setRenderParameter(String key, String value) {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called");
}
super.setRenderParameter(key, value);
this.redirectAllowed = false;
}
public void setRenderParameter(String key, String[] values) {
if (this.redirectedUrl != null) {
throw new IllegalStateException("Cannot set render parameters after sendRedirect has been called");
}
super.setRenderParameter(key, values);
this.redirectAllowed = false;
}
public void sendRedirect(String location) throws IOException {
if (!this.redirectAllowed) {
throw new IllegalStateException(
"Cannot call sendRedirect after windowState, portletMode, or renderParameters have been set");
}
Assert.notNull(location, "Redirect URL must not be null");
this.redirectedUrl = location;
}
public void sendRedirect(String location, String renderUrlParamName) throws IOException {
sendRedirect(location);
if (renderUrlParamName != null) {
setRenderParameter(renderUrlParamName, location);
}
}
public String getRedirectedUrl() {
return this.redirectedUrl;
}
}

View File

@@ -0,0 +1,152 @@
/*
* 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.portlet;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.portlet.BaseURL;
import javax.portlet.PortletSecurityException;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
/**
* Mock implementation of the {@link javax.portlet.BaseURL} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public abstract class MockBaseURL implements BaseURL {
public static final String URL_TYPE_RENDER = "render";
public static final String URL_TYPE_ACTION = "action";
private static final String ENCODING = "UTF-8";
protected final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
private boolean secure = false;
private final Map<String, String[]> properties = new LinkedHashMap<String, String[]>();
//---------------------------------------------------------------------
// BaseURL methods
//---------------------------------------------------------------------
public void setParameter(String key, String value) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(value, "Parameter value must not be null");
this.parameters.put(key, new String[] {value});
}
public void setParameter(String key, String[] values) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(values, "Parameter values must not be null");
this.parameters.put(key, values);
}
public void setParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.parameters.clear();
this.parameters.putAll(parameters);
}
public Set<String> getParameterNames() {
return this.parameters.keySet();
}
public String getParameter(String name) {
String[] arr = this.parameters.get(name);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getParameterValues(String name) {
return this.parameters.get(name);
}
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
public void setSecure(boolean secure) throws PortletSecurityException {
this.secure = secure;
}
public boolean isSecure() {
return this.secure;
}
public void write(Writer out) throws IOException {
out.write(toString());
}
public void write(Writer out, boolean escapeXML) throws IOException {
out.write(toString());
}
public void addProperty(String key, String value) {
String[] values = this.properties.get(key);
if (values != null) {
this.properties.put(key, StringUtils.addStringToArray(values, value));
}
else {
this.properties.put(key, new String[] {value});
}
}
public void setProperty(String key, String value) {
this.properties.put(key, new String[] {value});
}
public Map<String, String[]> getProperties() {
return Collections.unmodifiableMap(this.properties);
}
protected String encodeParameter(String name, String value) {
try {
return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING);
}
catch (UnsupportedEncodingException ex) {
return null;
}
}
protected String encodeParameter(String name, String[] values) {
try {
StringBuilder sb = new StringBuilder();
for (int i = 0, n = values.length; i < n; i++) {
sb.append(i > 0 ? ";" : "").append(URLEncoder.encode(name, ENCODING)).append("=")
.append(URLEncoder.encode(values[i], ENCODING));
}
return sb.toString();
}
catch (UnsupportedEncodingException ex) {
return null;
}
}
}

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.mock.web.portlet;
import javax.portlet.CacheControl;
/**
* Mock implementation of the {@link javax.portlet.CacheControl} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockCacheControl implements CacheControl {
private int expirationTime = 0;
private boolean publicScope = false;
private String etag;
private boolean useCachedContent = false;
public int getExpirationTime() {
return this.expirationTime;
}
public void setExpirationTime(int time) {
this.expirationTime = time;
}
public boolean isPublicScope() {
return this.publicScope;
}
public void setPublicScope(boolean publicScope) {
this.publicScope = publicScope;
}
public String getETag() {
return this.etag;
}
public void setETag(String token) {
this.etag = token;
}
public boolean useCachedContent() {
return this.useCachedContent;
}
public void setUseCachedContent(boolean useCachedContent) {
this.useCachedContent = useCachedContent;
}
}

View File

@@ -0,0 +1,128 @@
/*
* 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.portlet;
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 javax.portlet.ClientDataRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
/**
* Mock implementation of the {@link javax.portlet.ClientDataRequest} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockClientDataRequest extends MockPortletRequest implements ClientDataRequest {
private String characterEncoding;
private byte[] content;
private String contentType;
private String method;
/**
* Create a new MockClientDataRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public MockClientDataRequest() {
super();
}
/**
* Create a new MockClientDataRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
*/
public MockClientDataRequest(PortletContext portletContext) {
super(portletContext);
}
/**
* Create a new MockClientDataRequest.
* @param portalContext the PortalContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockClientDataRequest(PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
}
public void setContent(byte[] content) {
this.content = content;
}
public InputStream getPortletInputStream() throws IOException {
if (this.content != null) {
return new ByteArrayInputStream(this.content);
}
else {
return null;
}
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
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 String getCharacterEncoding() {
return this.characterEncoding;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getContentType() {
return this.contentType;
}
public int getContentLength() {
return (this.content != null ? content.length : -1);
}
public void setMethod(String method) {
this.method = method;
}
public String getMethod() {
return this.method;
}
}

View File

@@ -0,0 +1,88 @@
/*
* 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.portlet;
import java.io.Serializable;
import javax.portlet.Event;
import javax.xml.namespace.QName;
/**
* Mock implementation of the {@link javax.portlet.Event} interface.
*
* @author Juergen Hoeller
* @since 3.0
* @see MockEventRequest
*/
public class MockEvent implements Event {
private final QName name;
private final Serializable value;
/**
* Create a new MockEvent with the given name.
* @param name the name of the event
*/
public MockEvent(QName name) {
this.name = name;
this.value = null;
}
/**
* Create a new MockEvent with the given name and value.
* @param name the name of the event
* @param value the associated payload of the event
*/
public MockEvent(QName name, Serializable value) {
this.name = name;
this.value = value;
}
/**
* Create a new MockEvent with the given name.
* @param name the name of the event
*/
public MockEvent(String name) {
this.name = new QName(name);
this.value = null;
}
/**
* Create a new MockEvent with the given name and value.
* @param name the name of the event
* @param value the associated payload of the event
*/
public MockEvent(String name, Serializable value) {
this.name = new QName(name);
this.value = value;
}
public QName getQName() {
return this.name;
}
public String getName() {
return this.name.getLocalPart();
}
public Serializable getValue() {
return this.value;
}
}

View File

@@ -0,0 +1,88 @@
/*
* 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.portlet;
import javax.portlet.Event;
import javax.portlet.EventRequest;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
/**
* Mock implementation of the {@link javax.portlet.EventRequest} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockEventRequest extends MockPortletRequest implements EventRequest {
private final Event event;
private String method;
/**
* Create a new MockEventRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param event the event that this request wraps
* @see MockEvent
*/
public MockEventRequest(Event event) {
super();
this.event = event;
}
/**
* Create a new MockEventRequest with a default {@link MockPortalContext}.
* @param event the event that this request wraps
* @param portletContext the PortletContext that the request runs in
* @see MockEvent
*/
public MockEventRequest(Event event, PortletContext portletContext) {
super(portletContext);
this.event = event;
}
/**
* Create a new MockEventRequest.
* @param event the event that this request wraps
* @param portalContext the PortletContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockEventRequest(Event event, PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
this.event = event;
}
@Override
protected String getLifecyclePhase() {
return EVENT_PHASE;
}
public Event getEvent() {
return this.event;
}
public void setMethod(String method) {
this.method = method;
}
public String getMethod() {
return this.method;
}
}

View File

@@ -0,0 +1,34 @@
/*
* 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.portlet;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
/**
* Mock implementation of the {@link javax.portlet.EventResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockEventResponse extends MockStateAwareResponse implements EventResponse {
public void setRenderParameters(EventRequest request) {
setRenderParameters(request.getParameterMap());
}
}

View File

@@ -0,0 +1,243 @@
/*
* 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.portlet;
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.Collections;
import java.util.Enumeration;
import java.util.Locale;
import javax.portlet.CacheControl;
import javax.portlet.MimeResponse;
import javax.portlet.PortalContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletURL;
import javax.portlet.ResourceURL;
import org.springframework.util.CollectionUtils;
import org.springframework.web.util.WebUtils;
/**
* Mock implementation of the {@link javax.portlet.MimeResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockMimeResponse extends MockPortletResponse implements MimeResponse {
private PortletRequest request;
private String contentType;
private String characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
private PrintWriter writer;
private Locale locale = Locale.getDefault();
private int bufferSize = 4096;
private final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
private final CacheControl cacheControl = new MockCacheControl();
private boolean committed;
private String includedUrl;
private String forwardedUrl;
/**
* Create a new MockMimeResponse with a default {@link MockPortalContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
*/
public MockMimeResponse() {
super();
}
/**
* Create a new MockMimeResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockMimeResponse(PortalContext portalContext) {
super(portalContext);
}
/**
* Create a new MockMimeResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
* @param request the corresponding render/resource request that this response
* is being generated for
*/
public MockMimeResponse(PortalContext portalContext, PortletRequest request) {
super(portalContext);
this.request = request;
}
//---------------------------------------------------------------------
// RenderResponse methods
//---------------------------------------------------------------------
public void setContentType(String contentType) {
if (this.request != null) {
Enumeration<String> supportedTypes = this.request.getResponseContentTypes();
if (!CollectionUtils.contains(supportedTypes, contentType)) {
throw new IllegalArgumentException("Content type [" + contentType + "] not in supported list: " +
Collections.list(supportedTypes));
}
}
this.contentType = contentType;
}
public String getContentType() {
return this.contentType;
}
public void setCharacterEncoding(String characterEncoding) {
this.characterEncoding = characterEncoding;
}
public String getCharacterEncoding() {
return this.characterEncoding;
}
public PrintWriter getWriter() throws UnsupportedEncodingException {
if (this.writer == null) {
Writer targetWriter = (this.characterEncoding != null
? new OutputStreamWriter(this.outputStream, this.characterEncoding)
: new OutputStreamWriter(this.outputStream));
this.writer = new PrintWriter(targetWriter);
}
return this.writer;
}
public byte[] getContentAsByteArray() {
flushBuffer();
return this.outputStream.toByteArray();
}
public String getContentAsString() throws UnsupportedEncodingException {
flushBuffer();
return (this.characterEncoding != null)
? this.outputStream.toString(this.characterEncoding)
: this.outputStream.toString();
}
public void setLocale(Locale locale) {
this.locale = locale;
}
public Locale getLocale() {
return this.locale;
}
public void setBufferSize(int bufferSize) {
this.bufferSize = bufferSize;
}
public int getBufferSize() {
return this.bufferSize;
}
public void flushBuffer() {
if (this.writer != null) {
this.writer.flush();
}
if (this.outputStream != null) {
try {
this.outputStream.flush();
}
catch (IOException ex) {
throw new IllegalStateException("Could not flush OutputStream: " + ex.getMessage());
}
}
this.committed = true;
}
public void resetBuffer() {
if (this.committed) {
throw new IllegalStateException("Cannot reset buffer - response is already committed");
}
this.outputStream.reset();
}
public void setCommitted(boolean committed) {
this.committed = committed;
}
public boolean isCommitted() {
return this.committed;
}
public void reset() {
resetBuffer();
this.characterEncoding = null;
this.contentType = null;
this.locale = null;
}
public OutputStream getPortletOutputStream() throws IOException {
return this.outputStream;
}
public PortletURL createRenderURL() {
return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_RENDER);
}
public PortletURL createActionURL() {
return new MockPortletURL(getPortalContext(), MockPortletURL.URL_TYPE_ACTION);
}
public ResourceURL createResourceURL() {
return new MockResourceURL();
}
public CacheControl getCacheControl() {
return this.cacheControl;
}
//---------------------------------------------------------------------
// Methods for MockPortletRequestDispatcher
//---------------------------------------------------------------------
public void setIncludedUrl(String includedUrl) {
this.includedUrl = includedUrl;
}
public String getIncludedUrl() {
return this.includedUrl;
}
public void setForwardedUrl(String forwardedUrl) {
this.forwardedUrl = forwardedUrl;
}
public String getForwardedUrl() {
return this.forwardedUrl;
}
}

View File

@@ -0,0 +1,95 @@
/*
* 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.portlet;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
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.portlet.multipart.MultipartActionRequest;
/**
* Mock implementation of the
* {@link org.springframework.web.portlet.multipart.MultipartActionRequest} interface.
*
* <p>Useful for testing application controllers that access multipart uploads.
* The {@link org.springframework.mock.web.MockMultipartFile} can be used to
* populate these mock requests with files.
*
* @author Juergen Hoeller
* @author Arjen Poutsma
* @since 2.0
* @see org.springframework.mock.web.MockMultipartFile
*/
public class MockMultipartActionRequest extends MockActionRequest implements MultipartActionRequest {
private final MultiValueMap<String, MultipartFile> multipartFiles =
new LinkedMultiValueMap<String, MultipartFile>();
/**
* Add a file to this request. The parameter name from the multipart
* form is taken from the {@link org.springframework.web.multipart.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;
}
}
}

View File

@@ -0,0 +1,101 @@
/*
* 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.portlet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.WindowState;
/**
* Mock implementation of the {@link javax.portlet.PortalContext} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortalContext implements PortalContext {
private final Map<String, String> properties = new HashMap<String, String>();
private final List<PortletMode> portletModes;
private final List<WindowState> windowStates;
/**
* Create a new MockPortalContext
* with default PortletModes (VIEW, EDIT, HELP)
* and default WindowStates (NORMAL, MAXIMIZED, MINIMIZED).
* @see javax.portlet.PortletMode
* @see javax.portlet.WindowState
*/
public MockPortalContext() {
this.portletModes = new ArrayList<PortletMode>(3);
this.portletModes.add(PortletMode.VIEW);
this.portletModes.add(PortletMode.EDIT);
this.portletModes.add(PortletMode.HELP);
this.windowStates = new ArrayList<WindowState>(3);
this.windowStates.add(WindowState.NORMAL);
this.windowStates.add(WindowState.MAXIMIZED);
this.windowStates.add(WindowState.MINIMIZED);
}
/**
* Create a new MockPortalContext with the given PortletModes and WindowStates.
* @param supportedPortletModes the List of supported PortletMode instances
* @param supportedWindowStates the List of supported WindowState instances
* @see javax.portlet.PortletMode
* @see javax.portlet.WindowState
*/
public MockPortalContext(List<PortletMode> supportedPortletModes, List<WindowState> supportedWindowStates) {
this.portletModes = new ArrayList<PortletMode>(supportedPortletModes);
this.windowStates = new ArrayList<WindowState>(supportedWindowStates);
}
public String getPortalInfo() {
return "MockPortal/1.0";
}
public void setProperty(String name, String value) {
this.properties.put(name, value);
}
public String getProperty(String name) {
return this.properties.get(name);
}
public Enumeration<String> getPropertyNames() {
return Collections.enumeration(this.properties.keySet());
}
public Enumeration<PortletMode> getSupportedPortletModes() {
return Collections.enumeration(this.portletModes);
}
public Enumeration<WindowState> getSupportedWindowStates() {
return Collections.enumeration(this.windowStates);
}
}

View File

@@ -0,0 +1,183 @@
/*
* 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.portlet;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Set;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.xml.XMLConstants;
import javax.xml.namespace.QName;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.portlet.PortletConfig} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletConfig implements PortletConfig {
private final PortletContext portletContext;
private final String portletName;
private final Map<Locale, ResourceBundle> resourceBundles = new HashMap<Locale, ResourceBundle>();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
private final Set<String> publicRenderParameterNames = new LinkedHashSet<String>();
private String defaultNamespace = XMLConstants.NULL_NS_URI;
private final Set<QName> publishingEventQNames = new LinkedHashSet<QName>();
private final Set<QName> processingEventQNames = new LinkedHashSet<QName>();
private final Set<Locale> supportedLocales = new LinkedHashSet<Locale>();
private final Map<String, String[]> containerRuntimeOptions = new LinkedHashMap<String, String[]>();
/**
* Create a new MockPortletConfig with a default {@link MockPortletContext}.
*/
public MockPortletConfig() {
this(null, "");
}
/**
* Create a new MockPortletConfig with a default {@link MockPortletContext}.
* @param portletName the name of the portlet
*/
public MockPortletConfig(String portletName) {
this(null, portletName);
}
/**
* Create a new MockPortletConfig.
* @param portletContext the PortletContext that the portlet runs in
*/
public MockPortletConfig(PortletContext portletContext) {
this(portletContext, "");
}
/**
* Create a new MockPortletConfig.
* @param portletContext the PortletContext that the portlet runs in
* @param portletName the name of the portlet
*/
public MockPortletConfig(PortletContext portletContext, String portletName) {
this.portletContext = (portletContext != null ? portletContext : new MockPortletContext());
this.portletName = portletName;
}
public String getPortletName() {
return this.portletName;
}
public PortletContext getPortletContext() {
return this.portletContext;
}
public void setResourceBundle(Locale locale, ResourceBundle resourceBundle) {
Assert.notNull(locale, "Locale must not be null");
this.resourceBundles.put(locale, resourceBundle);
}
public ResourceBundle getResourceBundle(Locale locale) {
Assert.notNull(locale, "Locale must not be null");
return this.resourceBundles.get(locale);
}
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());
}
public void addPublicRenderParameterName(String name) {
this.publicRenderParameterNames.add(name);
}
public Enumeration<String> getPublicRenderParameterNames() {
return Collections.enumeration(this.publicRenderParameterNames);
}
public void setDefaultNamespace(String defaultNamespace) {
this.defaultNamespace = defaultNamespace;
}
public String getDefaultNamespace() {
return this.defaultNamespace;
}
public void addPublishingEventQName(QName name) {
this.publishingEventQNames.add(name);
}
public Enumeration<QName> getPublishingEventQNames() {
return Collections.enumeration(this.publishingEventQNames);
}
public void addProcessingEventQName(QName name) {
this.processingEventQNames.add(name);
}
public Enumeration<QName> getProcessingEventQNames() {
return Collections.enumeration(this.processingEventQNames);
}
public void addSupportedLocale(Locale locale) {
this.supportedLocales.add(locale);
}
public Enumeration<Locale> getSupportedLocales() {
return Collections.enumeration(this.supportedLocales);
}
public void addContainerRuntimeOption(String key, String value) {
this.containerRuntimeOptions.put(key, new String[] {value});
}
public void addContainerRuntimeOption(String key, String[] values) {
this.containerRuntimeOptions.put(key, values);
}
public Map<String, String[]> getContainerRuntimeOptions() {
return Collections.unmodifiableMap(this.containerRuntimeOptions);
}
}

View File

@@ -0,0 +1,265 @@
/*
* 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.portlet;
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.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequestDispatcher;
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.web.util.WebUtils;
/**
* Mock implementation of the {@link javax.portlet.PortletContext} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletContext implements PortletContext {
private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir";
private final Log logger = LogFactory.getLog(getClass());
private final String resourceBasePath;
private final ResourceLoader resourceLoader;
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
private String portletContextName = "MockPortletContext";
private Set<String> containerRuntimeOptions = new LinkedHashSet<String>();
/**
* Create a new MockPortletContext with no base path and a
* DefaultResourceLoader (i.e. the classpath root as WAR root).
* @see org.springframework.core.io.DefaultResourceLoader
*/
public MockPortletContext() {
this("", null);
}
/**
* Create a new MockPortletContext using a DefaultResourceLoader.
* @param resourceBasePath the WAR root directory (should not end with a slash)
* @see org.springframework.core.io.DefaultResourceLoader
*/
public MockPortletContext(String resourceBasePath) {
this(resourceBasePath, null);
}
/**
* Create a new MockPortletContext, using the specified ResourceLoader
* and no base path.
* @param resourceLoader the ResourceLoader to use (or null for the default)
*/
public MockPortletContext(ResourceLoader resourceLoader) {
this("", resourceLoader);
}
/**
* Create a new MockPortletContext.
* @param resourceBasePath the WAR root directory (should not end with a slash)
* @param resourceLoader the ResourceLoader to use (or null for the default)
*/
public MockPortletContext(String resourceBasePath, ResourceLoader resourceLoader) {
this.resourceBasePath = (resourceBasePath != null ? resourceBasePath : "");
this.resourceLoader = (resourceLoader != null ? resourceLoader : new DefaultResourceLoader());
// Use JVM temp dir as PortletContext 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 MockPortletContext.
* @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 String getServerInfo() {
return "MockPortal/1.0";
}
public PortletRequestDispatcher getRequestDispatcher(String path) {
if (!path.startsWith("/")) {
throw new IllegalArgumentException(
"PortletRequestDispatcher path at PortletContext level must start with '/'");
}
return new MockPortletRequestDispatcher(path);
}
public PortletRequestDispatcher getNamedDispatcher(String path) {
return null;
}
public InputStream getResourceAsStream(String path) {
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
try {
return resource.getInputStream();
}
catch (IOException ex) {
logger.info("Couldn't open InputStream for " + resource, ex);
return null;
}
}
public int getMajorVersion() {
return 2;
}
public int getMinorVersion() {
return 0;
}
public String getMimeType(String filePath) {
return null;
}
public String getRealPath(String path) {
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
try {
return resource.getFile().getAbsolutePath();
}
catch (IOException ex) {
logger.info("Couldn't determine real path of resource " + resource, ex);
return null;
}
}
public Set<String> getResourcePaths(String path) {
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
try {
File file = resource.getFile();
String[] fileList = file.list();
String prefix = (path.endsWith("/") ? path : path + "/");
Set<String> resourcePaths = new HashSet<String>(fileList.length);
for (String fileEntry : fileList) {
resourcePaths.add(prefix + fileEntry);
}
return resourcePaths;
}
catch (IOException ex) {
logger.info("Couldn't get resource paths for " + resource, ex);
return null;
}
}
public URL getResource(String path) throws MalformedURLException {
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
try {
return resource.getURL();
}
catch (IOException ex) {
logger.info("Couldn't get URL for " + resource, ex);
return null;
}
}
public Object getAttribute(String name) {
return this.attributes.get(name);
}
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public void setAttribute(String name, Object value) {
if (value != null) {
this.attributes.put(name, value);
}
else {
this.attributes.remove(name);
}
}
public void removeAttribute(String name) {
this.attributes.remove(name);
}
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());
}
public void log(String message) {
logger.info(message);
}
public void log(String message, Throwable t) {
logger.info(message, t);
}
public void setPortletContextName(String portletContextName) {
this.portletContextName = portletContextName;
}
public String getPortletContextName() {
return this.portletContextName;
}
public void addContainerRuntimeOption(String key) {
this.containerRuntimeOptions.add(key);
}
public Enumeration<String> getContainerRuntimeOptions() {
return Collections.enumeration(this.containerRuntimeOptions);
}
}

View File

@@ -0,0 +1,114 @@
/*
* 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.portlet;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortletPreferences;
import javax.portlet.PreferencesValidator;
import javax.portlet.ReadOnlyException;
import javax.portlet.ValidatorException;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.portlet.PortletPreferences} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletPreferences implements PortletPreferences {
private PreferencesValidator preferencesValidator;
private final Map<String, String[]> preferences = new LinkedHashMap<String, String[]>();
private final Set<String> readOnly = new HashSet<String>();
public void setReadOnly(String key, boolean readOnly) {
Assert.notNull(key, "Key must not be null");
if (readOnly) {
this.readOnly.add(key);
}
else {
this.readOnly.remove(key);
}
}
public boolean isReadOnly(String key) {
Assert.notNull(key, "Key must not be null");
return this.readOnly.contains(key);
}
public String getValue(String key, String def) {
Assert.notNull(key, "Key must not be null");
String[] values = this.preferences.get(key);
return (values != null && values.length > 0 ? values[0] : def);
}
public String[] getValues(String key, String[] def) {
Assert.notNull(key, "Key must not be null");
String[] values = this.preferences.get(key);
return (values != null && values.length > 0 ? values : def);
}
public void setValue(String key, String value) throws ReadOnlyException {
setValues(key, new String[] {value});
}
public void setValues(String key, String[] values) throws ReadOnlyException {
Assert.notNull(key, "Key must not be null");
if (isReadOnly(key)) {
throw new ReadOnlyException("Preference '" + key + "' is read-only");
}
this.preferences.put(key, values);
}
public Enumeration<String> getNames() {
return Collections.enumeration(this.preferences.keySet());
}
public Map<String, String[]> getMap() {
return Collections.unmodifiableMap(this.preferences);
}
public void reset(String key) throws ReadOnlyException {
Assert.notNull(key, "Key must not be null");
if (isReadOnly(key)) {
throw new ReadOnlyException("Preference '" + key + "' is read-only");
}
this.preferences.remove(key);
}
public void setPreferencesValidator(PreferencesValidator preferencesValidator) {
this.preferencesValidator = preferencesValidator;
}
public void store() throws IOException, ValidatorException {
if (this.preferencesValidator != null) {
this.preferencesValidator.validate(this);
}
}
}

View File

@@ -0,0 +1,527 @@
/*
* 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.portlet;
import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
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.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.WindowState;
import javax.servlet.http.Cookie;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Mock implementation of the {@link javax.portlet.PortletRequest} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletRequest implements PortletRequest {
private boolean active = true;
private final PortalContext portalContext;
private final PortletContext portletContext;
private PortletSession session;
private WindowState windowState = WindowState.NORMAL;
private PortletMode portletMode = PortletMode.VIEW;
private PortletPreferences portletPreferences = new MockPortletPreferences();
private final Map<String, List<String>> properties = new LinkedHashMap<String, List<String>>();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
private String authType = null;
private String contextPath = "";
private String remoteUser = null;
private Principal userPrincipal = null;
private final Set<String> userRoles = new HashSet<String>();
private boolean secure = false;
private boolean requestedSessionIdValid = true;
private final List<String> responseContentTypes = new LinkedList<String>();
private final List<Locale> locales = new LinkedList<Locale>();
private String scheme = "http";
private String serverName = "localhost";
private int serverPort = 80;
private String windowID;
private Cookie[] cookies;
private final Set<String> publicParameterNames = new HashSet<String>();
/**
* Create a new MockPortletRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see MockPortalContext
* @see MockPortletContext
*/
public MockPortletRequest() {
this(null, null);
}
/**
* Create a new MockPortletRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
* @see MockPortalContext
*/
public MockPortletRequest(PortletContext portletContext) {
this(null, portletContext);
}
/**
* Create a new MockPortletRequest.
* @param portalContext the PortalContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockPortletRequest(PortalContext portalContext, PortletContext portletContext) {
this.portalContext = (portalContext != null ? portalContext : new MockPortalContext());
this.portletContext = (portletContext != null ? portletContext : new MockPortletContext());
this.responseContentTypes.add("text/html");
this.locales.add(Locale.ENGLISH);
this.attributes.put(LIFECYCLE_PHASE, getLifecyclePhase());
}
//---------------------------------------------------------------------
// Lifecycle methods
//---------------------------------------------------------------------
/**
* Return the Portlet 2.0 lifecycle id for the current phase.
*/
protected String getLifecyclePhase() {
return null;
}
/**
* Return whether this request is still active (that is, not completed yet).
*/
public boolean isActive() {
return this.active;
}
/**
* Mark this request as completed.
*/
public void close() {
this.active = false;
}
/**
* 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");
}
}
//---------------------------------------------------------------------
// PortletRequest methods
//---------------------------------------------------------------------
public boolean isWindowStateAllowed(WindowState windowState) {
return CollectionUtils.contains(this.portalContext.getSupportedWindowStates(), windowState);
}
public boolean isPortletModeAllowed(PortletMode portletMode) {
return CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode);
}
public void setPortletMode(PortletMode portletMode) {
Assert.notNull(portletMode, "PortletMode must not be null");
this.portletMode = portletMode;
}
public PortletMode getPortletMode() {
return this.portletMode;
}
public void setWindowState(WindowState windowState) {
Assert.notNull(windowState, "WindowState must not be null");
this.windowState = windowState;
}
public WindowState getWindowState() {
return this.windowState;
}
public void setPreferences(PortletPreferences preferences) {
Assert.notNull(preferences, "PortletPreferences must not be null");
this.portletPreferences = preferences;
}
public PortletPreferences getPreferences() {
return this.portletPreferences;
}
public void setSession(PortletSession session) {
this.session = session;
if (session instanceof MockPortletSession) {
MockPortletSession mockSession = ((MockPortletSession) session);
mockSession.access();
}
}
public PortletSession getPortletSession() {
return getPortletSession(true);
}
public PortletSession getPortletSession(boolean create) {
checkActive();
// Reset session if invalidated.
if (this.session instanceof MockPortletSession && ((MockPortletSession) this.session).isInvalid()) {
this.session = null;
}
// Create new session if necessary.
if (this.session == null && create) {
this.session = new MockPortletSession(this.portletContext);
}
return this.session;
}
/**
* Set a single value for the specified property.
* <p>If there are already one or more values registered for the given
* property key, they will be replaced.
*/
public void setProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
List<String> list = new LinkedList<String>();
list.add(value);
this.properties.put(key, list);
}
/**
* Add a single value for the specified property.
* <p>If there are already one or more values registered for the given
* property key, the given value will be added to the end of the list.
*/
public void addProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
List<String> oldList = this.properties.get(key);
if (oldList != null) {
oldList.add(value);
}
else {
List<String> list = new LinkedList<String>();
list.add(value);
this.properties.put(key, list);
}
}
public String getProperty(String key) {
Assert.notNull(key, "Property key must not be null");
List list = this.properties.get(key);
return (list != null && list.size() > 0 ? (String) list.get(0) : null);
}
public Enumeration<String> getProperties(String key) {
Assert.notNull(key, "property key must not be null");
return Collections.enumeration(this.properties.get(key));
}
public Enumeration<String> getPropertyNames() {
return Collections.enumeration(this.properties.keySet());
}
public PortalContext getPortalContext() {
return this.portalContext;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getAuthType() {
return this.authType;
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
public String getContextPath() {
return this.contextPath;
}
public void setRemoteUser(String remoteUser) {
this.remoteUser = remoteUser;
}
public String getRemoteUser() {
return this.remoteUser;
}
public void setUserPrincipal(Principal userPrincipal) {
this.userPrincipal = userPrincipal;
}
public Principal getUserPrincipal() {
return this.userPrincipal;
}
public void addUserRole(String role) {
this.userRoles.add(role);
}
public boolean isUserInRole(String role) {
return this.userRoles.contains(role);
}
public Object getAttribute(String name) {
checkActive();
return this.attributes.get(name);
}
public Enumeration<String> getAttributeNames() {
checkActive();
return Collections.enumeration(this.attributes.keySet());
}
public void setParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.parameters.clear();
this.parameters.putAll(parameters);
}
public void setParameter(String key, String value) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(value, "Parameter value must not be null");
this.parameters.put(key, new String[] {value});
}
public void setParameter(String key, String[] values) {
Assert.notNull(key, "Parameter key must be null");
Assert.notNull(values, "Parameter values must not be null");
this.parameters.put(key, values);
}
public void addParameter(String name, String value) {
addParameter(name, new String[] {value});
}
public void addParameter(String name, String[] values) {
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);
}
}
public String getParameter(String name) {
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) {
return this.parameters.get(name);
}
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
public void setSecure(boolean secure) {
this.secure = secure;
}
public boolean isSecure() {
return this.secure;
}
public void setAttribute(String name, Object value) {
checkActive();
if (value != null) {
this.attributes.put(name, value);
}
else {
this.attributes.remove(name);
}
}
public void removeAttribute(String name) {
checkActive();
this.attributes.remove(name);
}
public String getRequestedSessionId() {
PortletSession session = this.getPortletSession();
return (session != null ? session.getId() : null);
}
public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {
this.requestedSessionIdValid = requestedSessionIdValid;
}
public boolean isRequestedSessionIdValid() {
return this.requestedSessionIdValid;
}
public void addResponseContentType(String responseContentType) {
this.responseContentTypes.add(responseContentType);
}
public void addPreferredResponseContentType(String responseContentType) {
this.responseContentTypes.add(0, responseContentType);
}
public String getResponseContentType() {
return this.responseContentTypes.get(0);
}
public Enumeration<String> getResponseContentTypes() {
return Collections.enumeration(this.responseContentTypes);
}
public void addLocale(Locale locale) {
this.locales.add(locale);
}
public void addPreferredLocale(Locale locale) {
this.locales.add(0, locale);
}
public Locale getLocale() {
return this.locales.get(0);
}
public Enumeration<Locale> getLocales() {
return Collections.enumeration(this.locales);
}
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 void setWindowID(String windowID) {
this.windowID = windowID;
}
public String getWindowID() {
return this.windowID;
}
public void setCookies(Cookie... cookies) {
this.cookies = cookies;
}
public Cookie[] getCookies() {
return this.cookies;
}
public Map<String, String[]> getPrivateParameterMap() {
if (!this.publicParameterNames.isEmpty()) {
Map<String, String[]> filtered = new LinkedHashMap<String, String[]>();
for (String key : this.parameters.keySet()) {
if (!this.publicParameterNames.contains(key)) {
filtered.put(key, this.parameters.get(key));
}
}
return filtered;
}
else {
return Collections.unmodifiableMap(this.parameters);
}
}
public Map<String, String[]> getPublicParameterMap() {
if (!this.publicParameterNames.isEmpty()) {
Map<String, String[]> filtered = new LinkedHashMap<String, String[]>();
for (String key : this.parameters.keySet()) {
if (this.publicParameterNames.contains(key)) {
filtered.put(key, this.parameters.get(key));
}
}
return filtered;
}
else {
return Collections.emptyMap();
}
}
public void registerPublicParameter(String name) {
this.publicParameterNames.add(name);
}
}

View File

@@ -0,0 +1,84 @@
/*
* 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.portlet;
import java.io.IOException;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.portlet.PortletRequestDispatcher} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletRequestDispatcher implements PortletRequestDispatcher {
private final Log logger = LogFactory.getLog(getClass());
private final String url;
/**
* Create a new MockPortletRequestDispatcher for the given URL.
* @param url the URL to dispatch to.
*/
public MockPortletRequestDispatcher(String url) {
Assert.notNull(url, "URL must not be null");
this.url = url;
}
public void include(RenderRequest request, RenderResponse response) throws PortletException, IOException {
include((PortletRequest) request, (PortletResponse) response);
}
public void include(PortletRequest request, PortletResponse response) throws PortletException, IOException {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
if (!(response instanceof MockMimeResponse)) {
throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse");
}
((MockMimeResponse) response).setIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockPortletRequestDispatcher: including URL [" + this.url + "]");
}
}
public void forward(PortletRequest request, PortletResponse response) throws PortletException, IOException {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
if (!(response instanceof MockMimeResponse)) {
throw new IllegalArgumentException("MockPortletRequestDispatcher requires MockMimeResponse");
}
((MockMimeResponse) response).setForwardedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockPortletRequestDispatcher: forwarding to URL [" + this.url + "]");
}
}
}

View File

@@ -0,0 +1,195 @@
/*
* 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.portlet;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortalContext;
import javax.portlet.PortletResponse;
import javax.servlet.http.Cookie;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.portlet.PortletResponse} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletResponse implements PortletResponse {
private final PortalContext portalContext;
private final Map<String, String[]> properties = new LinkedHashMap<String, String[]>();
private String namespace = "";
private final Set<Cookie> cookies = new LinkedHashSet<Cookie>();
private final Map<String, Element[]> xmlProperties = new LinkedHashMap<String, Element[]>();
private Document xmlDocument;
/**
* Create a new MockPortletResponse with a default {@link MockPortalContext}.
* @see MockPortalContext
*/
public MockPortletResponse() {
this(null);
}
/**
* Create a new MockPortletResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockPortletResponse(PortalContext portalContext) {
this.portalContext = (portalContext != null ? portalContext : new MockPortalContext());
}
/**
* Return the PortalContext that this MockPortletResponse runs in,
* defining the supported PortletModes and WindowStates.
*/
public PortalContext getPortalContext() {
return this.portalContext;
}
//---------------------------------------------------------------------
// PortletResponse methods
//---------------------------------------------------------------------
public void addProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
String[] oldArr = this.properties.get(key);
if (oldArr != null) {
String[] newArr = new String[oldArr.length + 1];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
newArr[oldArr.length] = value;
this.properties.put(key, newArr);
}
else {
this.properties.put(key, new String[] {value});
}
}
public void setProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
this.properties.put(key, new String[] {value});
}
public Set<String> getPropertyNames() {
return Collections.unmodifiableSet(this.properties.keySet());
}
public String getProperty(String key) {
Assert.notNull(key, "Property key must not be null");
String[] arr = this.properties.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getProperties(String key) {
Assert.notNull(key, "Property key must not be null");
return this.properties.get(key);
}
public String encodeURL(String path) {
return path;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getNamespace() {
return this.namespace;
}
public void addProperty(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 void addProperty(String key, Element value) {
Assert.notNull(key, "Property key must not be null");
Element[] oldArr = this.xmlProperties.get(key);
if (oldArr != null) {
Element[] newArr = new Element[oldArr.length + 1];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
newArr[oldArr.length] = value;
this.xmlProperties.put(key, newArr);
}
else {
this.xmlProperties.put(key, new Element[] {value});
}
}
public Set<String> getXmlPropertyNames() {
return Collections.unmodifiableSet(this.xmlProperties.keySet());
}
public Element getXmlProperty(String key) {
Assert.notNull(key, "Property key must not be null");
Element[] arr = this.xmlProperties.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public Element[] getXmlProperties(String key) {
Assert.notNull(key, "Property key must not be null");
return this.xmlProperties.get(key);
}
public Element createElement(String tagName) throws DOMException {
if (this.xmlDocument == null) {
try {
this.xmlDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
}
catch (ParserConfigurationException ex) {
throw new DOMException(DOMException.INVALID_STATE_ERR, ex.toString());
}
}
return this.xmlDocument.createElement(tagName);
}
}

View File

@@ -0,0 +1,231 @@
/*
* 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.portlet;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.portlet.PortletContext;
import javax.portlet.PortletSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import org.springframework.mock.web.MockHttpSession;
/**
* Mock implementation of the {@link javax.portlet.PortletSession} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletSession implements PortletSession {
private static int nextId = 1;
private final String id = Integer.toString(nextId++);
private final long creationTime = System.currentTimeMillis();
private int maxInactiveInterval;
private long lastAccessedTime = System.currentTimeMillis();
private final PortletContext portletContext;
private final Map<String, Object> portletAttributes = new HashMap<String, Object>();
private final Map<String, Object> applicationAttributes = new HashMap<String, Object>();
private boolean invalid = false;
private boolean isNew = true;
/**
* Create a new MockPortletSession with a default {@link MockPortletContext}.
* @see MockPortletContext
*/
public MockPortletSession() {
this(null);
}
/**
* Create a new MockPortletSession.
* @param portletContext the PortletContext that the session runs in
*/
public MockPortletSession(PortletContext portletContext) {
this.portletContext = (portletContext != null ? portletContext : new MockPortletContext());
}
public Object getAttribute(String name) {
return this.portletAttributes.get(name);
}
public Object getAttribute(String name, int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
return this.portletAttributes.get(name);
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
return this.applicationAttributes.get(name);
}
return null;
}
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.portletAttributes.keySet());
}
public Enumeration<String> getAttributeNames(int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
return Collections.enumeration(this.portletAttributes.keySet());
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
return Collections.enumeration(this.applicationAttributes.keySet());
}
return null;
}
public long getCreationTime() {
return this.creationTime;
}
public String getId() {
return this.id;
}
public void access() {
this.lastAccessedTime = System.currentTimeMillis();
setNew(false);
}
public long getLastAccessedTime() {
return this.lastAccessedTime;
}
public int getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
/**
* Clear all of this session's attributes.
*/
public void clearAttributes() {
doClearAttributes(this.portletAttributes);
doClearAttributes(this.applicationAttributes);
}
protected void doClearAttributes(Map<String, Object> attributes) {
for (Iterator<Map.Entry<String, Object>> it = 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(new MockHttpSession(), 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;
}
public void removeAttribute(String name) {
this.portletAttributes.remove(name);
}
public void removeAttribute(String name, int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
this.portletAttributes.remove(name);
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
this.applicationAttributes.remove(name);
}
}
public void setAttribute(String name, Object value) {
if (value != null) {
this.portletAttributes.put(name, value);
}
else {
this.portletAttributes.remove(name);
}
}
public void setAttribute(String name, Object value, int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
if (value != null) {
this.portletAttributes.put(name, value);
}
else {
this.portletAttributes.remove(name);
}
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
if (value != null) {
this.applicationAttributes.put(name, value);
}
else {
this.applicationAttributes.remove(name);
}
}
}
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
public PortletContext getPortletContext() {
return this.portletContext;
}
public Map<String, Object> getAttributeMap() {
return Collections.unmodifiableMap(this.portletAttributes);
}
public Map<String, Object> getAttributeMap(int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
return Collections.unmodifiableMap(this.portletAttributes);
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
return Collections.unmodifiableMap(this.applicationAttributes);
}
else {
return Collections.emptyMap();
}
}
}

View File

@@ -0,0 +1,115 @@
/*
* 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.portlet;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletURL;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Mock implementation of the {@link javax.portlet.PortletURL} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockPortletURL extends MockBaseURL implements PortletURL {
public static final String URL_TYPE_RENDER = "render";
public static final String URL_TYPE_ACTION = "action";
private final PortalContext portalContext;
private final String urlType;
private WindowState windowState;
private PortletMode portletMode;
/**
* Create a new MockPortletURL for the given URL type.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
* @param urlType the URL type, for example "render" or "action"
* @see #URL_TYPE_RENDER
* @see #URL_TYPE_ACTION
*/
public MockPortletURL(PortalContext portalContext, String urlType) {
Assert.notNull(portalContext, "PortalContext is required");
this.portalContext = portalContext;
this.urlType = urlType;
}
//---------------------------------------------------------------------
// PortletURL methods
//---------------------------------------------------------------------
public void setWindowState(WindowState windowState) throws WindowStateException {
if (!CollectionUtils.contains(this.portalContext.getSupportedWindowStates(), windowState)) {
throw new WindowStateException("WindowState not supported", windowState);
}
this.windowState = windowState;
}
public WindowState getWindowState() {
return this.windowState;
}
public void setPortletMode(PortletMode portletMode) throws PortletModeException {
if (!CollectionUtils.contains(this.portalContext.getSupportedPortletModes(), portletMode)) {
throw new PortletModeException("PortletMode not supported", portletMode);
}
this.portletMode = portletMode;
}
public PortletMode getPortletMode() {
return this.portletMode;
}
public void removePublicRenderParameter(String name) {
this.parameters.remove(name);
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(encodeParameter("urlType", this.urlType));
if (this.windowState != null) {
sb.append(";").append(encodeParameter("windowState", this.windowState.toString()));
}
if (this.portletMode != null) {
sb.append(";").append(encodeParameter("portletMode", this.portletMode.toString()));
}
for (Map.Entry<String, String[]> entry : this.parameters.entrySet()) {
sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue()));
}
return (isSecure() ? "https:" : "http:") +
"//localhost/mockportlet?" + sb.toString();
}
}

View File

@@ -0,0 +1,93 @@
/*
* 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.portlet;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.RenderRequest;
import javax.portlet.WindowState;
/**
* Mock implementation of the {@link javax.portlet.RenderRequest} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockRenderRequest extends MockPortletRequest implements RenderRequest {
/**
* Create a new MockRenderRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see MockPortalContext
* @see MockPortletContext
*/
public MockRenderRequest() {
super();
}
/**
* Create a new MockRenderRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param portletMode the mode that the portlet runs in
*/
public MockRenderRequest(PortletMode portletMode) {
super();
setPortletMode(portletMode);
}
/**
* Create a new MockRenderRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param portletMode the mode that the portlet runs in
* @param windowState the window state to run the portlet in
*/
public MockRenderRequest(PortletMode portletMode, WindowState windowState) {
super();
setPortletMode(portletMode);
setWindowState(windowState);
}
/**
* Create a new MockRenderRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
*/
public MockRenderRequest(PortletContext portletContext) {
super(portletContext);
}
/**
* Create a new MockRenderRequest.
* @param portalContext the PortletContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockRenderRequest(PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
}
@Override
protected String getLifecyclePhase() {
return RENDER_PHASE;
}
public String getETag() {
return getProperty(RenderRequest.ETAG);
}
}

View File

@@ -0,0 +1,88 @@
/*
* 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.portlet;
import java.util.Collection;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
/**
* Mock implementation of the {@link javax.portlet.RenderResponse} interface.
*
* @author John A. Lewis
* @author Juergen Hoeller
* @since 2.0
*/
public class MockRenderResponse extends MockMimeResponse implements RenderResponse {
private String title;
private Collection<PortletMode> nextPossiblePortletModes;
/**
* Create a new MockRenderResponse with a default {@link MockPortalContext}.
* @see MockPortalContext
*/
public MockRenderResponse() {
super();
}
/**
* Create a new MockRenderResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockRenderResponse(PortalContext portalContext) {
super(portalContext);
}
/**
* Create a new MockRenderResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
* @param request the corresponding render request that this response
* is generated for
*/
public MockRenderResponse(PortalContext portalContext, RenderRequest request) {
super(portalContext, request);
}
//---------------------------------------------------------------------
// RenderResponse methods
//---------------------------------------------------------------------
public void setTitle(String title) {
this.title = title;
}
public String getTitle() {
return this.title;
}
public void setNextPossiblePortletModes(Collection<PortletMode> portletModes) {
this.nextPossiblePortletModes = portletModes;
}
public Collection<PortletMode> getNextPossiblePortletModes() {
return this.nextPossiblePortletModes;
}
}

View File

@@ -0,0 +1,128 @@
/*
* 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.portlet;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.RenderRequest;
import javax.portlet.ResourceRequest;
/**
* Mock implementation of the {@link javax.portlet.ResourceRequest} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockResourceRequest extends MockClientDataRequest implements ResourceRequest {
private String resourceID;
private String cacheability;
private final Map<String, String[]> privateRenderParameterMap = new LinkedHashMap<String, String[]>();
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public MockResourceRequest() {
super();
}
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param resourceID the resource id for this request
*/
public MockResourceRequest(String resourceID) {
super();
this.resourceID = resourceID;
}
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}
* and a default {@link MockPortletContext}.
* @param url the resource URL for this request
*/
public MockResourceRequest(MockResourceURL url) {
super();
this.resourceID = url.getResourceID();
this.cacheability = url.getCacheability();
}
/**
* Create a new MockResourceRequest with a default {@link MockPortalContext}.
* @param portletContext the PortletContext that the request runs in
*/
public MockResourceRequest(PortletContext portletContext) {
super(portletContext);
}
/**
* Create a new MockResourceRequest.
* @param portalContext the PortalContext that the request runs in
* @param portletContext the PortletContext that the request runs in
*/
public MockResourceRequest(PortalContext portalContext, PortletContext portletContext) {
super(portalContext, portletContext);
}
@Override
protected String getLifecyclePhase() {
return RESOURCE_PHASE;
}
public void setResourceID(String resourceID) {
this.resourceID = resourceID;
}
public String getResourceID() {
return this.resourceID;
}
public void setCacheability(String cacheLevel) {
this.cacheability = cacheLevel;
}
public String getCacheability() {
return this.cacheability;
}
public String getETag() {
return getProperty(RenderRequest.ETAG);
}
public void addPrivateRenderParameter(String key, String value) {
this.privateRenderParameterMap.put(key, new String[] {value});
}
public void addPrivateRenderParameter(String key, String[] values) {
this.privateRenderParameterMap.put(key, values);
}
public Map<String, String[]> getPrivateRenderParameterMap() {
return Collections.unmodifiableMap(this.privateRenderParameterMap);
}
}

View File

@@ -0,0 +1,40 @@
/*
* 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.portlet;
import javax.portlet.ResourceResponse;
/**
* Mock implementation of the {@link javax.portlet.ResourceResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockResourceResponse extends MockMimeResponse implements ResourceResponse {
private int contentLength = 0;
public void setContentLength(int len) {
this.contentLength = len;
}
public int getContentLength() {
return this.contentLength;
}
}

View File

@@ -0,0 +1,69 @@
/*
* 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.portlet;
import java.util.Map;
import javax.portlet.ResourceURL;
/**
* Mock implementation of the {@link javax.portlet.ResourceURL} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockResourceURL extends MockBaseURL implements ResourceURL {
private String resourceID;
private String cacheability;
//---------------------------------------------------------------------
// ResourceURL methods
//---------------------------------------------------------------------
public void setResourceID(String resourceID) {
this.resourceID = resourceID;
}
public String getResourceID() {
return this.resourceID;
}
public void setCacheability(String cacheLevel) {
this.cacheability = cacheLevel;
}
public String getCacheability() {
return this.cacheability;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(encodeParameter("resourceID", this.resourceID));
if (this.cacheability != null) {
sb.append(";").append(encodeParameter("cacheability", this.cacheability));
}
for (Map.Entry<String, String[]> entry : this.parameters.entrySet()) {
sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue()));
}
return (isSecure() ? "https:" : "http:") +
"//localhost/mockportlet?" + sb.toString();
}
}

View File

@@ -0,0 +1,154 @@
/*
* 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.portlet;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.StateAwareResponse;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import javax.xml.namespace.QName;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Mock implementation of the {@link javax.portlet.StateAwareResponse} interface.
*
* @author Juergen Hoeller
* @since 3.0
*/
public class MockStateAwareResponse extends MockPortletResponse implements StateAwareResponse {
private WindowState windowState;
private PortletMode portletMode;
private final Map<String, String[]> renderParameters = new LinkedHashMap<String, String[]>();
private final Map<QName, Serializable> events = new HashMap<QName, Serializable>();
/**
* Create a new MockActionResponse with a default {@link MockPortalContext}.
* @see org.springframework.mock.web.portlet.MockPortalContext
*/
public MockStateAwareResponse() {
super();
}
/**
* Create a new MockActionResponse.
* @param portalContext the PortalContext defining the supported
* PortletModes and WindowStates
*/
public MockStateAwareResponse(PortalContext portalContext) {
super(portalContext);
}
public void setWindowState(WindowState windowState) throws WindowStateException {
if (!CollectionUtils.contains(getPortalContext().getSupportedWindowStates(), windowState)) {
throw new WindowStateException("WindowState not supported", windowState);
}
this.windowState = windowState;
}
public WindowState getWindowState() {
return this.windowState;
}
public void setPortletMode(PortletMode portletMode) throws PortletModeException {
if (!CollectionUtils.contains(getPortalContext().getSupportedPortletModes(), portletMode)) {
throw new PortletModeException("PortletMode not supported", portletMode);
}
this.portletMode = portletMode;
}
public PortletMode getPortletMode() {
return this.portletMode;
}
public void setRenderParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.renderParameters.clear();
this.renderParameters.putAll(parameters);
}
public void setRenderParameter(String key, String value) {
Assert.notNull(key, "Parameter key must not be null");
Assert.notNull(value, "Parameter value must not be null");
this.renderParameters.put(key, new String[] {value});
}
public void setRenderParameter(String key, String[] values) {
Assert.notNull(key, "Parameter key must not be null");
Assert.notNull(values, "Parameter values must not be null");
this.renderParameters.put(key, values);
}
public String getRenderParameter(String key) {
Assert.notNull(key, "Parameter key must not be null");
String[] arr = this.renderParameters.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getRenderParameterValues(String key) {
Assert.notNull(key, "Parameter key must not be null");
return this.renderParameters.get(key);
}
public Iterator<String> getRenderParameterNames() {
return this.renderParameters.keySet().iterator();
}
public Map<String, String[]> getRenderParameterMap() {
return Collections.unmodifiableMap(this.renderParameters);
}
public void removePublicRenderParameter(String name) {
this.renderParameters.remove(name);
}
public void setEvent(QName name, Serializable value) {
this.events.put(name, value);
}
public void setEvent(String name, Serializable value) {
this.events.put(new QName(name), value);
}
public Iterator<QName> getEventNames() {
return this.events.keySet().iterator();
}
public Serializable getEvent(QName name) {
return this.events.get(name);
}
public Serializable getEvent(String name) {
return this.events.get(new QName(name));
}
}

View File

@@ -0,0 +1,145 @@
/*
* 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.portlet;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequestDispatcher;
import javax.servlet.ServletContext;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.portlet.PortletContext} interface,
* wrapping an underlying {@link javax.servlet.ServletContext}.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.mock.web.portlet.MockPortletContext
*/
public class ServletWrappingPortletContext implements PortletContext {
private final ServletContext servletContext;
/**
* Create a new PortletContext wrapping the given ServletContext.
* @param servletContext the ServletContext to wrap
*/
public ServletWrappingPortletContext(ServletContext servletContext) {
Assert.notNull(servletContext, "ServletContext must not be null");
this.servletContext = servletContext;
}
/**
* Return the underlying ServletContext that this PortletContext wraps.
*/
public final ServletContext getServletContext() {
return this.servletContext;
}
public String getServerInfo() {
return this.servletContext.getServerInfo();
}
public PortletRequestDispatcher getRequestDispatcher(String path) {
return null;
}
public PortletRequestDispatcher getNamedDispatcher(String name) {
return null;
}
public InputStream getResourceAsStream(String path) {
return this.servletContext.getResourceAsStream(path);
}
public int getMajorVersion() {
return 2;
}
public int getMinorVersion() {
return 0;
}
public String getMimeType(String file) {
return this.servletContext.getMimeType(file);
}
public String getRealPath(String path) {
return this.servletContext.getRealPath(path);
}
@SuppressWarnings("unchecked")
public Set<String> getResourcePaths(String path) {
return this.servletContext.getResourcePaths(path);
}
public URL getResource(String path) throws MalformedURLException {
return this.servletContext.getResource(path);
}
public Object getAttribute(String name) {
return this.servletContext.getAttribute(name);
}
@SuppressWarnings("unchecked")
public Enumeration<String> getAttributeNames() {
return this.servletContext.getAttributeNames();
}
public String getInitParameter(String name) {
return this.servletContext.getInitParameter(name);
}
@SuppressWarnings("unchecked")
public Enumeration<String> getInitParameterNames() {
return this.servletContext.getInitParameterNames();
}
public void log(String msg) {
this.servletContext.log(msg);
}
public void log(String message, Throwable throwable) {
this.servletContext.log(message, throwable);
}
public void removeAttribute(String name) {
this.servletContext.removeAttribute(name);
}
public void setAttribute(String name, Object object) {
this.servletContext.setAttribute(name, object);
}
public String getPortletContextName() {
return this.servletContext.getServletContextName();
}
public Enumeration<String> getContainerRuntimeOptions() {
return Collections.enumeration(new HashSet<String>());
}
}

View File

@@ -0,0 +1,11 @@
/**
* A comprehensive set of Portlet API mock objects,
* targeted at usage with Spring's web MVC framework.
* Useful for testing web contexts and controllers.
*
* <p>More convenient to use than dynamic mock objects
* (<a href="http://www.easymock.org">EasyMock</a>) or
* existing Portlet API mock objects.
*/
package org.springframework.mock.web.portlet;

View File

@@ -0,0 +1,508 @@
/*
* 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.portlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.EventRequest;
import javax.portlet.EventResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.ConstructorArgumentValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.core.Ordered;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.portlet.bind.PortletRequestBindingException;
import org.springframework.web.portlet.context.PortletRequestHandledEvent;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import org.springframework.web.portlet.handler.HandlerInterceptorAdapter;
import org.springframework.web.portlet.handler.ParameterHandlerMapping;
import org.springframework.web.portlet.handler.ParameterMappingInterceptor;
import org.springframework.web.portlet.handler.PortletModeHandlerMapping;
import org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping;
import org.springframework.web.portlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.portlet.handler.SimplePortletHandlerAdapter;
import org.springframework.web.portlet.handler.SimplePortletPostProcessor;
import org.springframework.web.portlet.handler.UserRoleAuthorizationInterceptor;
import org.springframework.web.portlet.multipart.DefaultMultipartActionRequest;
import org.springframework.web.portlet.multipart.MultipartActionRequest;
import org.springframework.web.portlet.multipart.PortletMultipartResolver;
import org.springframework.web.portlet.mvc.Controller;
import org.springframework.web.portlet.mvc.SimpleControllerHandlerAdapter;
/**
* @author Juergen Hoeller
* @author Mark Fisher
* @author Arjen Poutsma
*/
public class ComplexPortletApplicationContext extends StaticPortletApplicationContext {
public void refresh() throws BeansException {
registerSingleton("standardHandlerAdapter", SimpleControllerHandlerAdapter.class);
registerSingleton("portletHandlerAdapter", SimplePortletHandlerAdapter.class);
registerSingleton("myHandlerAdapter", MyHandlerAdapter.class);
registerSingleton("viewController", ViewController.class);
registerSingleton("editController", EditController.class);
registerSingleton("helpController1", HelpController1.class);
registerSingleton("helpController2", HelpController2.class);
registerSingleton("testController1", TestController1.class);
registerSingleton("testController2", TestController2.class);
registerSingleton("requestLocaleCheckingController", RequestLocaleCheckingController.class);
registerSingleton("localeContextCheckingController", LocaleContextCheckingController.class);
registerSingleton("exceptionThrowingHandler1", ExceptionThrowingHandler.class);
registerSingleton("exceptionThrowingHandler2", ExceptionThrowingHandler.class);
registerSingleton("unknownHandler", Object.class);
registerSingleton("myPortlet", MyPortlet.class);
registerSingleton("portletMultipartResolver", MockMultipartResolver.class);
registerSingleton("portletPostProcessor", SimplePortletPostProcessor.class);
registerSingleton("testListener", TestApplicationListener.class);
ConstructorArgumentValues cvs = new ConstructorArgumentValues();
cvs.addIndexedArgumentValue(0, new MockPortletContext());
cvs.addIndexedArgumentValue(1, "complex");
registerBeanDefinition("portletConfig", new RootBeanDefinition(MockPortletConfig.class, cvs, null));
UserRoleAuthorizationInterceptor userRoleInterceptor = new UserRoleAuthorizationInterceptor();
userRoleInterceptor.setAuthorizedRoles(new String[] {"role1", "role2"});
ParameterHandlerMapping interceptingHandlerMapping = new ParameterHandlerMapping();
interceptingHandlerMapping.setParameterName("interceptingParam");
ParameterMappingInterceptor parameterMappingInterceptor = new ParameterMappingInterceptor();
parameterMappingInterceptor.setParameterName("interceptingParam");
List interceptors = new ArrayList();
interceptors.add(parameterMappingInterceptor);
interceptors.add(userRoleInterceptor);
interceptors.add(new MyHandlerInterceptor1());
interceptors.add(new MyHandlerInterceptor2());
MutablePropertyValues pvs = new MutablePropertyValues();
Map portletModeMap = new ManagedMap();
portletModeMap.put("view", new RuntimeBeanReference("viewController"));
portletModeMap.put("edit", new RuntimeBeanReference("editController"));
pvs.add("portletModeMap", portletModeMap);
pvs.add("interceptors", interceptors);
registerSingleton("handlerMapping3", PortletModeHandlerMapping.class, pvs);
pvs = new MutablePropertyValues();
Map parameterMap = new ManagedMap();
parameterMap.put("test1", new RuntimeBeanReference("testController1"));
parameterMap.put("test2", new RuntimeBeanReference("testController2"));
parameterMap.put("requestLocaleChecker", new RuntimeBeanReference("requestLocaleCheckingController"));
parameterMap.put("contextLocaleChecker", new RuntimeBeanReference("localeContextCheckingController"));
parameterMap.put("exception1", new RuntimeBeanReference("exceptionThrowingHandler1"));
parameterMap.put("exception2", new RuntimeBeanReference("exceptionThrowingHandler2"));
parameterMap.put("myPortlet", new RuntimeBeanReference("myPortlet"));
parameterMap.put("unknown", new RuntimeBeanReference("unknownHandler"));
pvs.add("parameterMap", parameterMap);
pvs.add("parameterName", "myParam");
pvs.add("order", "2");
registerSingleton("handlerMapping2", ParameterHandlerMapping.class, pvs);
pvs = new MutablePropertyValues();
Map innerMap = new ManagedMap();
innerMap.put("help1", new RuntimeBeanReference("helpController1"));
innerMap.put("help2", new RuntimeBeanReference("helpController2"));
Map outerMap = new ManagedMap();
outerMap.put("help", innerMap);
pvs.add("portletModeParameterMap", outerMap);
pvs.add("order", "1");
registerSingleton("handlerMapping1", PortletModeParameterHandlerMapping.class, pvs);
pvs = new MutablePropertyValues();
pvs.add("order", "1");
pvs.add("exceptionMappings",
"java.lang.IllegalAccessException=failed-illegalaccess\n" +
"PortletRequestBindingException=failed-binding\n" +
"NoHandlerFoundException=failed-unavailable");
pvs.add("defaultErrorView", "failed-default-1");
registerSingleton("exceptionResolver", SimpleMappingExceptionResolver.class, pvs);
pvs = new MutablePropertyValues();
pvs.add("order", "0");
pvs.add("exceptionMappings",
"java.lang.Exception=failed-exception\n" +
"java.lang.RuntimeException=failed-runtime");
List mappedHandlers = new ManagedList();
mappedHandlers.add(new RuntimeBeanReference("exceptionThrowingHandler1"));
pvs.add("mappedHandlers", mappedHandlers);
pvs.add("defaultErrorView", "failed-default-0");
registerSingleton("handlerExceptionResolver", SimpleMappingExceptionResolver.class, pvs);
addMessage("test", Locale.ENGLISH, "test message");
addMessage("test", Locale.CANADA, "Canadian & test message");
addMessage("test.args", Locale.ENGLISH, "test {0} and {1}");
super.refresh();
}
public static class TestController1 implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) {
response.setRenderParameter("result", "test1-action");
}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception {
return null;
}
}
public static class TestController2 implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) {}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception {
response.setProperty("result", "test2-view");
return null;
}
}
public static class ViewController implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) {}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception {
return new ModelAndView("someViewName", "result", "view was here");
}
}
public static class EditController implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) {
response.setRenderParameter("param", "edit was here");
}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception {
return new ModelAndView(request.getParameter("param"));
}
}
public static class HelpController1 implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) {
response.setRenderParameter("param", "help1 was here");
}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception {
return new ModelAndView("help1-view");
}
}
public static class HelpController2 implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) {
response.setRenderParameter("param", "help2 was here");
}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response) throws Exception {
return new ModelAndView("help2-view");
}
}
public static class RequestLocaleCheckingController implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) throws PortletException {
if (!Locale.CANADA.equals(request.getLocale())) {
throw new PortletException("Incorrect Locale in ActionRequest");
}
}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
if (!Locale.CANADA.equals(request.getLocale())) {
throw new PortletException("Incorrect Locale in RenderRequest");
}
response.getWriter().write("locale-ok");
return null;
}
}
public static class LocaleContextCheckingController implements Controller {
public void handleActionRequest(ActionRequest request, ActionResponse response) throws PortletException {
if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
throw new PortletException("Incorrect Locale in LocaleContextHolder");
}
}
public ModelAndView handleRenderRequest(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
throw new PortletException("Incorrect Locale in LocaleContextHolder");
}
response.getWriter().write("locale-ok");
return null;
}
}
public static class MyPortlet implements Portlet {
private PortletConfig portletConfig;
public void init(PortletConfig portletConfig) throws PortletException {
this.portletConfig = portletConfig;
}
public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
response.setRenderParameter("result", "myPortlet action called");
}
public void render(RenderRequest request, RenderResponse response) throws PortletException, IOException {
response.getWriter().write("myPortlet was here");
}
public PortletConfig getPortletConfig() {
return this.portletConfig;
}
public void destroy() {
this.portletConfig = null;
}
}
public static interface MyHandler {
public void doSomething(PortletRequest request) throws Exception;
}
public static class ExceptionThrowingHandler implements MyHandler {
public void doSomething(PortletRequest request) throws Exception {
if (request.getParameter("fail") != null) {
throw new ModelAndViewDefiningException(new ModelAndView("failed-modelandview"));
}
if (request.getParameter("access") != null) {
throw new IllegalAccessException("portlet-illegalaccess");
}
if (request.getParameter("binding") != null) {
throw new PortletRequestBindingException("portlet-binding");
}
if (request.getParameter("generic") != null) {
throw new Exception("portlet-generic");
}
if (request.getParameter("runtime") != null) {
throw new RuntimeException("portlet-runtime");
}
throw new IllegalArgumentException("illegal argument");
}
}
public static class MyHandlerAdapter implements HandlerAdapter, Ordered {
public int getOrder() {
return 99;
}
public boolean supports(Object handler) {
return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
}
public void handleAction(ActionRequest request, ActionResponse response, Object delegate) throws Exception {
((MyHandler) delegate).doSomething(request);
}
public ModelAndView handleRender(RenderRequest request, RenderResponse response, Object delegate) throws Exception {
((MyHandler) delegate).doSomething(request);
return null;
}
public ModelAndView handleResource(ResourceRequest request, ResourceResponse response, Object handler)
throws Exception {
return null;
}
public void handleEvent(EventRequest request, EventResponse response, Object handler) throws Exception {
}
}
public static class MyHandlerInterceptor1 extends HandlerInterceptorAdapter {
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler)
throws PortletException {
if (request.getAttribute("test2-remove-never") != null) {
throw new PortletException("Wrong interceptor order");
}
request.setAttribute("test1-remove-never", "test1-remove-never");
request.setAttribute("test1-remove-post", "test1-remove-post");
request.setAttribute("test1-remove-after", "test1-remove-after");
return true;
}
public void postHandleRender(
RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView)
throws PortletException {
if (request.getAttribute("test2-remove-post") != null) {
throw new PortletException("Wrong interceptor order");
}
if (!"test1-remove-post".equals(request.getAttribute("test1-remove-post"))) {
throw new PortletException("Incorrect request attribute");
}
request.removeAttribute("test1-remove-post");
}
public void afterRenderCompletion(
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws PortletException {
if (request.getAttribute("test2-remove-after") != null) {
throw new PortletException("Wrong interceptor order");
}
request.removeAttribute("test1-remove-after");
}
}
public static class MyHandlerInterceptor2 extends HandlerInterceptorAdapter {
public boolean preHandleRender(RenderRequest request, RenderResponse response, Object handler)
throws PortletException {
if (request.getAttribute("test1-remove-post") == null) {
throw new PortletException("Wrong interceptor order");
}
if ("true".equals(request.getParameter("abort"))) {
return false;
}
request.setAttribute("test2-remove-never", "test2-remove-never");
request.setAttribute("test2-remove-post", "test2-remove-post");
request.setAttribute("test2-remove-after", "test2-remove-after");
return true;
}
public void postHandleRender(
RenderRequest request, RenderResponse response, Object handler, ModelAndView modelAndView)
throws PortletException {
if ("true".equals(request.getParameter("noView"))) {
modelAndView.clear();
}
if (request.getAttribute("test1-remove-post") == null) {
throw new PortletException("Wrong interceptor order");
}
if (!"test2-remove-post".equals(request.getAttribute("test2-remove-post"))) {
throw new PortletException("Incorrect request attribute");
}
request.removeAttribute("test2-remove-post");
}
public void afterRenderCompletion(
RenderRequest request, RenderResponse response, Object handler, Exception ex)
throws Exception {
if (request.getAttribute("test1-remove-after") == null) {
throw new PortletException("Wrong interceptor order");
}
request.removeAttribute("test2-remove-after");
}
}
public static class MultipartCheckingHandler implements MyHandler {
public void doSomething(PortletRequest request) throws PortletException, IllegalAccessException {
if (!(request instanceof MultipartActionRequest)) {
throw new PortletException("Not in a MultipartActionRequest");
}
}
}
public static class MockMultipartResolver implements PortletMultipartResolver {
public boolean isMultipart(ActionRequest request) {
return true;
}
public MultipartActionRequest resolveMultipart(ActionRequest request) throws MultipartException {
if (request.getAttribute("fail") != null) {
throw new MaxUploadSizeExceededException(1000);
}
if (request instanceof MultipartActionRequest) {
throw new IllegalStateException("Already a multipart request");
}
if (request.getAttribute("resolved") != null) {
throw new IllegalStateException("Already resolved");
}
request.setAttribute("resolved", Boolean.TRUE);
MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>();
files.set("someFile", new MockMultipartFile("someFile", "someContent".getBytes()));
Map<String, String[]> params = new HashMap<String, String[]>();
params.put("someParam", new String[] {"someParam"});
return new DefaultMultipartActionRequest(request, files, params, Collections.<String, String>emptyMap());
}
public void cleanupMultipart(MultipartActionRequest request) {
if (request.getAttribute("cleanedUp") != null) {
throw new IllegalStateException("Already cleaned up");
}
request.setAttribute("cleanedUp", Boolean.TRUE);
}
}
public static class TestApplicationListener implements ApplicationListener {
public int counter = 0;
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof PortletRequestHandledEvent) {
this.counter++;
}
}
}
}

View File

@@ -0,0 +1,978 @@
/*
* 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.portlet;
import java.io.IOException;
import java.util.Locale;
import java.util.Map;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletSecurityException;
import javax.portlet.PortletSession;
import javax.portlet.UnavailableException;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.i18n.LocaleContext;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletSession;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.portlet.context.PortletApplicationContextUtils;
import org.springframework.web.portlet.context.PortletConfigAwareBean;
import org.springframework.web.portlet.context.PortletContextAwareBean;
import org.springframework.web.portlet.context.PortletRequestAttributes;
import org.springframework.web.portlet.handler.PortletSessionRequiredException;
import org.springframework.web.portlet.multipart.MultipartActionRequest;
import org.springframework.web.portlet.multipart.PortletMultipartResolver;
import org.springframework.web.servlet.ViewRendererServlet;
import org.springframework.web.servlet.view.InternalResourceView;
/**
* @author Mark Fisher
* @author Juergen Hoeller
* @author Dan McCallum
*/
public class DispatcherPortletTests extends TestCase {
private MockPortletConfig simplePortletConfig;
private MockPortletConfig complexPortletConfig;
private DispatcherPortlet simpleDispatcherPortlet;
private DispatcherPortlet complexDispatcherPortlet;
protected void setUp() throws PortletException {
simplePortletConfig = new MockPortletConfig(new MockPortletContext(), "simple");
complexPortletConfig = new MockPortletConfig(simplePortletConfig.getPortletContext(), "complex");
complexPortletConfig.addInitParameter("publishContext", "false");
simpleDispatcherPortlet = new DispatcherPortlet();
simpleDispatcherPortlet.setContextClass(SimplePortletApplicationContext.class);
simpleDispatcherPortlet.init(simplePortletConfig);
complexDispatcherPortlet = new DispatcherPortlet();
complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class);
complexDispatcherPortlet.setNamespace("test");
complexDispatcherPortlet.addRequiredProperty("publishContext");
complexDispatcherPortlet.init(complexPortletConfig);
}
private PortletContext getPortletContext() {
return complexPortletConfig.getPortletContext();
}
public void testDispatcherPortletGetPortletNameDoesNotFailWithoutConfig() {
DispatcherPortlet dp = new DispatcherPortlet();
assertEquals(null, dp.getPortletConfig());
assertEquals(null, dp.getPortletName());
assertEquals(null, dp.getPortletContext());
}
public void testDispatcherPortlets() {
assertTrue("Correct namespace",
("simple" + FrameworkPortlet.DEFAULT_NAMESPACE_SUFFIX).equals(simpleDispatcherPortlet.getNamespace()));
assertTrue("Correct attribute",
(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "simple").equals(simpleDispatcherPortlet.getPortletContextAttributeName()));
assertTrue("Context published",
simpleDispatcherPortlet.getPortletApplicationContext() ==
getPortletContext().getAttribute(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "simple"));
assertTrue("Correct namespace", "test".equals(complexDispatcherPortlet.getNamespace()));
assertTrue("Correct attribute",
(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "complex").equals(complexDispatcherPortlet.getPortletContextAttributeName()));
assertTrue("Context not published",
getPortletContext().getAttribute(FrameworkPortlet.PORTLET_CONTEXT_PREFIX + "complex") == null);
}
public void testSimpleValidActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("action", "form");
request.setParameter("age", "29");
simpleDispatcherPortlet.processAction(request, response);
String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNull(exceptionParam);
SimplePortletApplicationContext ac = (SimplePortletApplicationContext)simpleDispatcherPortlet.getPortletApplicationContext();
String commandAttribute = ac.getRenderCommandSessionAttributeName();
TestBean testBean = (TestBean) request.getPortletSession().getAttribute(commandAttribute);
assertEquals(39, testBean.getAge());
}
public void testSimpleInvalidActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("action", "invalid");
simpleDispatcherPortlet.processAction(request, response);
String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNotNull(exceptionParam);
assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName()));
}
public void testSimpleFormViewNoBindOnNewForm() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("action", "form");
request.setParameter("age", "29");
simpleDispatcherPortlet.doDispatch(request, response);
assertEquals("5", response.getContentAsString());
}
public void testSimpleFormViewBindOnNewForm() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("action", "form-bind");
request.setParameter("age", "29");
simpleDispatcherPortlet.doDispatch(request, response);
assertEquals("34", response.getContentAsString());
}
public void testSimpleFormViewWithSessionAndBindOnNewForm() throws Exception {
MockRenderRequest renderRequest = new MockRenderRequest();
MockRenderResponse renderResponse = new MockRenderResponse();
renderRequest.setParameter("action", "form-session-bind");
renderRequest.setParameter("age", "30");
TestBean testBean = new TestBean();
testBean.setAge(40);
SimplePortletApplicationContext ac =
(SimplePortletApplicationContext)simpleDispatcherPortlet.getPortletApplicationContext();
String formAttribute = ac.getFormSessionAttributeName();
PortletSession session = new MockPortletSession();
session.setAttribute(formAttribute, testBean);
renderRequest.setSession(session);
simpleDispatcherPortlet.doDispatch(renderRequest, renderResponse);
assertEquals("35", renderResponse.getContentAsString());
}
public void testSimpleFormViewWithSessionNoBindOnNewForm() throws Exception {
MockActionRequest actionRequest = new MockActionRequest();
MockActionResponse actionResponse = new MockActionResponse();
actionRequest.setSession(new MockPortletSession());
actionRequest.setParameter("action", "form-session-nobind");
actionRequest.setParameter("age", "27");
simpleDispatcherPortlet.processAction(actionRequest, actionResponse);
Map renderParameters = actionResponse.getRenderParameterMap();
MockRenderRequest renderRequest = new MockRenderRequest();
MockRenderResponse renderResponse = new MockRenderResponse();
renderRequest.setParameters(renderParameters);
renderRequest.setParameter("action", "form-session-nobind");
renderRequest.setParameter("age", "30");
renderRequest.setSession(actionRequest.getPortletSession());
simpleDispatcherPortlet.doDispatch(renderRequest, renderResponse);
assertEquals("finished42", renderResponse.getContentAsString());
}
public void testSimpleRequiredSessionFormWithoutSession() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("action", "form-session-bind");
try {
simpleDispatcherPortlet.doDispatch(request, response);
fail("Should have thrown PortletSessionRequiredException");
}
catch (PortletSessionRequiredException ex) {
// expected
}
}
public void testSimpleFormSubmission() throws Exception {
MockActionRequest actionRequest = new MockActionRequest();
MockActionResponse actionResponse = new MockActionResponse();
actionRequest.setParameter("action", "form");
actionRequest.setParameter("age", "29");
simpleDispatcherPortlet.processAction(actionRequest, actionResponse);
MockRenderRequest renderRequest = new MockRenderRequest();
MockRenderResponse renderResponse = new MockRenderResponse();
renderRequest.setSession(actionRequest.getPortletSession());
renderRequest.setParameters(actionResponse.getRenderParameterMap());
renderRequest.setParameter("action", "form");
simpleDispatcherPortlet.doDispatch(renderRequest, renderResponse);
assertEquals("finished44", renderResponse.getContentAsString());
}
public void testSimpleFormSubmissionWithValidationError() throws Exception {
MockActionRequest actionRequest = new MockActionRequest();
MockActionResponse actionResponse = new MockActionResponse();
actionRequest.setParameter("action", "form");
actionRequest.setParameter("age", "XX");
simpleDispatcherPortlet.processAction(actionRequest, actionResponse);
MockRenderRequest renderRequest = new MockRenderRequest();
MockRenderResponse renderResponse = new MockRenderResponse();
renderRequest.setSession(actionRequest.getPortletSession());
renderRequest.setParameters(actionResponse.getRenderParameterMap());
renderRequest.setParameter("action", "form");
simpleDispatcherPortlet.doDispatch(renderRequest, renderResponse);
assertEquals("5", renderResponse.getContentAsString());
}
public void testSimpleInvalidRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("action", "invalid");
try {
simpleDispatcherPortlet.doDispatch(request, response);
fail("Should have thrown UnavailableException");
}
catch (NoHandlerFoundException ex) {
// expected
}
}
public void testPortletModeParameterMappingHelp1() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.HELP);
request.setParameter("action", "help1");
complexDispatcherPortlet.processAction(request, response);
String param = response.getRenderParameter("param");
assertEquals("help1 was here", param);
}
public void testPortletModeParameterMappingHelp2() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.HELP);
request.setParameter("action", "help2");
complexDispatcherPortlet.processAction(request, response);
String param = response.getRenderParameter("param");
assertEquals("help2 was here", param);
}
public void testPortletModeParameterMappingInvalidHelpActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.HELP);
request.setParameter("action", "help3");
complexDispatcherPortlet.processAction(request, response);
String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNotNull(exceptionParam);
assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName()));
}
public void testPortletModeParameterMappingInvalidHelpRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.HELP);
request.setParameter("action", "help3");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
assertTrue(model.get("exception").getClass().equals(NoHandlerFoundException.class));
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-unavailable", view.getBeanName());
}
public void testPortletModeMappingValidEditActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.EDIT);
request.addUserRole("role1");
request.setParameter("action", "not mapped");
request.setParameter("myParam", "not mapped");
complexDispatcherPortlet.processAction(request, response);
assertEquals("edit was here", response.getRenderParameter("param"));
}
public void testPortletModeMappingEditActionRequestWithUnauthorizedUserRole() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.EDIT);
request.addUserRole("role3");
request.setParameter("action", "not mapped");
request.setParameter("myParam", "not mapped");
complexDispatcherPortlet.processAction(request, response);
String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNotNull(exception);
String name = PortletSecurityException.class.getName();
assertTrue(exception.startsWith(name));
}
public void testPortletModeMappingValidViewRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role2");
request.setParameter("action", "not mapped");
request.setParameter("myParam", "not mapped");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
assertEquals("view was here", model.get("result"));
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("someViewName", view.getBeanName());
}
public void testPortletModeMappingViewRenderRequestWithUnauthorizedUserRole() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role3");
request.setParameter("action", "not mapped");
request.setParameter("myParam", "not mapped");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
Exception exception = (Exception) model.get("exception");
assertNotNull(exception);
assertTrue(exception.getClass().equals(PortletSecurityException.class));
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testParameterMappingValidActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.EDIT);
request.setParameter("action", "not mapped");
request.setParameter("myParam", "test1");
complexDispatcherPortlet.processAction(request, response);
assertEquals("test1-action", response.getRenderParameter("result"));
}
public void testParameterMappingValidRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.setParameter("action", "not mapped");
request.setParameter("myParam", "test2");
complexDispatcherPortlet.doDispatch(request, response);
assertEquals("test2-view", response.getProperty("result"));
}
public void testUnknownHandlerActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("myParam", "unknown");
complexDispatcherPortlet.processAction(request, response);
String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNotNull(exceptionParam);
assertTrue(exceptionParam.startsWith(PortletException.class.getName()));
assertTrue(exceptionParam.indexOf("No adapter for handler") != -1);
}
public void testUnknownHandlerRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "unknown");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
Exception exception = (Exception)model.get("exception");
assertTrue(exception.getClass().equals(PortletException.class));
assertTrue(exception.getMessage().indexOf("No adapter for handler") != -1);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testNoDetectAllHandlerMappingsWithPortletModeActionRequest() throws Exception {
DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet();
complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class);
complexDispatcherPortlet.setNamespace("test");
complexDispatcherPortlet.setDetectAllHandlerMappings(false);
complexDispatcherPortlet.init(new MockPortletConfig(getPortletContext(), "complex"));
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.EDIT);
complexDispatcherPortlet.processAction(request, response);
String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNotNull(exceptionParam);
assertTrue(exceptionParam.startsWith(NoHandlerFoundException.class.getName()));
}
public void testNoDetectAllHandlerMappingsWithParameterRenderRequest() throws Exception {
DispatcherPortlet complexDispatcherPortlet = new DispatcherPortlet();
complexDispatcherPortlet.setContextClass(ComplexPortletApplicationContext.class);
complexDispatcherPortlet.setNamespace("test");
complexDispatcherPortlet.setDetectAllHandlerMappings(false);
complexDispatcherPortlet.init(new MockPortletConfig(getPortletContext(), "complex"));
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "test1");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
Exception exception = (Exception) model.get("exception");
assertTrue(exception.getClass().equals(NoHandlerFoundException.class));
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-unavailable", view.getBeanName());
}
public void testExistingMultipartRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.EDIT);
ComplexPortletApplicationContext.MockMultipartResolver multipartResolver =
(ComplexPortletApplicationContext.MockMultipartResolver)
complexDispatcherPortlet.getPortletApplicationContext().getBean("portletMultipartResolver");
MultipartActionRequest multipartRequest = multipartResolver.resolveMultipart(request);
complexDispatcherPortlet.processAction(multipartRequest, response);
multipartResolver.cleanupMultipart(multipartRequest);
assertNotNull(request.getAttribute("cleanedUp"));
}
public void testMultipartResolutionFailed() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.EDIT);
request.addUserRole("role1");
request.setAttribute("fail", Boolean.TRUE);
complexDispatcherPortlet.processAction(request, response);
String exception = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertTrue(exception.startsWith(MaxUploadSizeExceededException.class.getName()));
}
public void testActionRequestHandledEvent() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
complexDispatcherPortlet.processAction(request, response);
ComplexPortletApplicationContext.TestApplicationListener listener =
(ComplexPortletApplicationContext.TestApplicationListener)
complexDispatcherPortlet.getPortletApplicationContext().getBean("testListener");
assertEquals(1, listener.counter);
}
public void testRenderRequestHandledEvent() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
ComplexPortletApplicationContext.TestApplicationListener listener =
(ComplexPortletApplicationContext.TestApplicationListener)
complexDispatcherPortlet.getPortletApplicationContext().getBean("testListener");
assertEquals(1, listener.counter);
}
public void testPublishEventsOff() throws Exception {
complexDispatcherPortlet.setPublishEvents(false);
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("action", "checker");
complexDispatcherPortlet.processAction(request, response);
ComplexPortletApplicationContext.TestApplicationListener listener =
(ComplexPortletApplicationContext.TestApplicationListener)
complexDispatcherPortlet.getPortletApplicationContext().getBean("testListener");
assertEquals(0, listener.counter);
}
public void testCorrectLocaleInRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "requestLocaleChecker");
request.addPreferredLocale(Locale.CANADA);
complexDispatcherPortlet.doDispatch(request, response);
assertEquals("locale-ok", response.getContentAsString());
}
public void testIncorrectLocaleInRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "requestLocaleChecker");
request.addPreferredLocale(Locale.ENGLISH);
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
Exception exception = (Exception) model.get("exception");
assertTrue(exception.getClass().equals(PortletException.class));
assertEquals("Incorrect Locale in RenderRequest", exception.getMessage());
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testCorrectLocaleInLocaleContextHolder() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "contextLocaleChecker");
request.addPreferredLocale(Locale.CANADA);
complexDispatcherPortlet.doDispatch(request, response);
assertEquals("locale-ok", response.getContentAsString());
}
public void testIncorrectLocaleInLocalContextHolder() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "contextLocaleChecker");
request.addPreferredLocale(Locale.ENGLISH);
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
Exception exception = (Exception) model.get("exception");
assertTrue(exception.getClass().equals(PortletException.class));
assertEquals("Incorrect Locale in LocaleContextHolder", exception.getMessage());
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testHandlerInterceptorNoAbort() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role1");
request.addParameter("abort", "false");
complexDispatcherPortlet.doDispatch(request, response);
assertTrue(request.getAttribute("test1-remove-never") != null);
assertTrue(request.getAttribute("test1-remove-post") == null);
assertTrue(request.getAttribute("test1-remove-after") == null);
assertTrue(request.getAttribute("test2-remove-never") != null);
assertTrue(request.getAttribute("test2-remove-post") == null);
assertTrue(request.getAttribute("test2-remove-after") == null);
}
public void testHandlerInterceptorAbort() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role1");
request.addParameter("abort", "true");
complexDispatcherPortlet.doDispatch(request, response);
assertTrue(request.getAttribute("test1-remove-never") != null);
assertTrue(request.getAttribute("test1-remove-post") != null);
assertTrue(request.getAttribute("test1-remove-after") == null);
assertTrue(request.getAttribute("test2-remove-never") == null);
assertTrue(request.getAttribute("test2-remove-post") == null);
assertTrue(request.getAttribute("test2-remove-after") == null);
}
public void testHandlerInterceptorNotClearingModelAndView() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role1");
request.addParameter("noView", "false");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
assertEquals("view was here", model.get("result"));
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("someViewName", view.getBeanName());
}
public void testHandlerInterceptorClearingModelAndView() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role1");
request.addParameter("noView", "true");
complexDispatcherPortlet.doDispatch(request, response);
Map model = (Map) request.getAttribute(ViewRendererServlet.MODEL_ATTRIBUTE);
assertNull(model);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertNull(view);
}
public void testParameterMappingInterceptorWithCorrectParam() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role1");
request.addParameter("interceptingParam", "test1");
complexDispatcherPortlet.processAction(request, response);
assertEquals("test1", response.getRenderParameter("interceptingParam"));
}
public void testParameterMappingInterceptorWithIncorrectParam() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setPortletMode(PortletMode.VIEW);
request.addUserRole("role1");
request.addParameter("incorrect", "test1");
complexDispatcherPortlet.processAction(request, response);
assertNull(response.getRenderParameter("incorrect"));
assertNull(response.getRenderParameter("interceptingParam"));
}
public void testPortletHandlerAdapterActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("myParam", "myPortlet");
complexDispatcherPortlet.processAction(request, response);
assertEquals("myPortlet action called", response.getRenderParameter("result"));
ComplexPortletApplicationContext.MyPortlet myPortlet =
(ComplexPortletApplicationContext.MyPortlet) complexDispatcherPortlet.getPortletApplicationContext().getBean("myPortlet");
assertEquals("complex", myPortlet.getPortletConfig().getPortletName());
assertEquals(getPortletContext(), myPortlet.getPortletConfig().getPortletContext());
assertEquals(complexDispatcherPortlet.getPortletContext(), myPortlet.getPortletConfig().getPortletContext());
complexDispatcherPortlet.destroy();
assertNull(myPortlet.getPortletConfig());
}
public void testPortletHandlerAdapterRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setParameter("myParam", "myPortlet");
complexDispatcherPortlet.doDispatch(request, response);
assertEquals("myPortlet was here", response.getContentAsString());
ComplexPortletApplicationContext.MyPortlet myPortlet =
(ComplexPortletApplicationContext.MyPortlet)
complexDispatcherPortlet.getPortletApplicationContext().getBean("myPortlet");
assertEquals("complex", myPortlet.getPortletConfig().getPortletName());
assertEquals(getPortletContext(), myPortlet.getPortletConfig().getPortletContext());
assertEquals(complexDispatcherPortlet.getPortletContext(),
myPortlet.getPortletConfig().getPortletContext());
complexDispatcherPortlet.destroy();
assertNull(myPortlet.getPortletConfig());
}
public void testModelAndViewDefiningExceptionInMappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception1");
request.addParameter("fail", "yes");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-modelandview", view.getBeanName());
}
public void testModelAndViewDefiningExceptionInUnmappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception2");
request.addParameter("fail", "yes");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-modelandview", view.getBeanName());
}
public void testIllegalAccessExceptionInMappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception1");
request.addParameter("access", "illegal");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-exception", view.getBeanName());
}
public void testIllegalAccessExceptionInUnmappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception2");
request.addParameter("access", "illegal");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-illegalaccess", view.getBeanName());
}
public void testPortletRequestBindingExceptionInMappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception1");
request.addParameter("binding", "should fail");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-exception", view.getBeanName());
}
public void testPortletRequestBindingExceptionInUnmappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception2");
request.addParameter("binding", "should fail");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-binding", view.getBeanName());
}
public void testIllegalArgumentExceptionInMappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception1");
request.addParameter("unknown", "");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-runtime", view.getBeanName());
}
public void testIllegalArgumentExceptionInUnmappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception2");
request.addParameter("unknown", "");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testExceptionInMappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception1");
request.addParameter("generic", "123");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-exception", view.getBeanName());
}
public void testExceptionInUnmappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception2");
request.addParameter("generic", "123");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testRuntimeExceptionInMappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception1");
request.addParameter("runtime", "true");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-runtime", view.getBeanName());
}
public void testRuntimeExceptionInUnmappedHandler() throws Exception {
MockRenderRequest request = new MockRenderRequest();
request.setPortletMode(PortletMode.HELP);
request.addParameter("myParam", "exception2");
request.addParameter("runtime", "true");
MockRenderResponse response = new MockRenderResponse();
complexDispatcherPortlet.doDispatch(request, response);
InternalResourceView view = (InternalResourceView) request.getAttribute(ViewRendererServlet.VIEW_ATTRIBUTE);
assertEquals("failed-default-1", view.getBeanName());
}
public void testGetMessage() {
String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test", null, Locale.ENGLISH);
assertEquals("test message", message);
}
public void testGetMessageOtherLocale() {
String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test", null, Locale.CANADA);
assertEquals("Canadian & test message", message);
}
public void testGetMessageWithArgs() {
Object[] args = new String[] {"this", "that"};
String message = complexDispatcherPortlet.getPortletApplicationContext().getMessage("test.args", args, Locale.ENGLISH);
assertEquals("test this and that", message);
}
public void testPortletApplicationContextLookup() {
MockPortletContext portletContext = new MockPortletContext();
ApplicationContext ac = PortletApplicationContextUtils.getWebApplicationContext(portletContext);
assertNull(ac);
try {
ac = PortletApplicationContextUtils.getRequiredWebApplicationContext(portletContext);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
portletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
new StaticWebApplicationContext());
try {
ac = PortletApplicationContextUtils.getRequiredWebApplicationContext(portletContext);
assertNotNull(ac);
}
catch (IllegalStateException ex) {
fail("Should not have thrown IllegalStateException: " + ex.getMessage());
}
}
public void testValidActionRequestWithExistingThreadLocalRequestContext() throws IOException, PortletException {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.addPreferredLocale(Locale.GERMAN);
request.setParameter("action", "form");
request.setParameter("age", "29");
// see RequestContextListener.requestInitialized()
try {
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(new PortletRequestAttributes(request));
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
simpleDispatcherPortlet.processAction(request, response);
assertSame(servletLocaleContext, LocaleContextHolder.getLocaleContext());
assertSame(servletRequestAttrs, RequestContextHolder.getRequestAttributes());
}
finally {
RequestContextHolder.resetRequestAttributes();
LocaleContextHolder.resetLocaleContext();
}
}
public void testValidRenderRequestWithExistingThreadLocalRequestContext() throws IOException, PortletException {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.addPreferredLocale(Locale.GERMAN);
// see RequestContextListener.requestInitialized()
try {
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(new PortletRequestAttributes(request));
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
request.setParameter("action", "form");
request.setParameter("age", "29");
simpleDispatcherPortlet.doDispatch(request, response);
assertSame(servletLocaleContext, LocaleContextHolder.getLocaleContext());
assertSame(servletRequestAttrs, RequestContextHolder.getRequestAttributes());
}
finally {
RequestContextHolder.resetRequestAttributes();
LocaleContextHolder.resetLocaleContext();
}
}
public void testInvalidActionRequestWithExistingThreadLocalRequestContext() throws IOException, PortletException {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.addPreferredLocale(Locale.GERMAN);
// see RequestContextListener.requestInitialized()
try {
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(new PortletRequestAttributes(request));
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
request.setParameter("action", "invalid");
simpleDispatcherPortlet.processAction(request, response);
String exceptionParam = response.getRenderParameter(DispatcherPortlet.ACTION_EXCEPTION_RENDER_PARAMETER);
assertNotNull(exceptionParam); // ensure that an exceptional condition occured
assertSame(servletLocaleContext, LocaleContextHolder.getLocaleContext());
assertSame(servletRequestAttrs, RequestContextHolder.getRequestAttributes());
}
finally {
RequestContextHolder.resetRequestAttributes();
LocaleContextHolder.resetLocaleContext();
}
}
public void testInvalidRenderRequestWithExistingThreadLocalRequestContext() throws IOException, PortletException {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.addPreferredLocale(Locale.GERMAN);
// see RequestContextListener.requestInitialized()
try {
LocaleContextHolder.setLocale(request.getLocale());
RequestContextHolder.setRequestAttributes(new PortletRequestAttributes(request));
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
try {
simpleDispatcherPortlet.doDispatch(request, response);
fail("should have failed to find a handler and raised an NoHandlerFoundExceptionException");
}
catch (NoHandlerFoundException ex) {
// expected
}
assertSame(servletLocaleContext, LocaleContextHolder.getLocaleContext());
assertSame(servletRequestAttrs, RequestContextHolder.getRequestAttributes());
}
finally {
RequestContextHolder.resetRequestAttributes();
LocaleContextHolder.resetLocaleContext();
}
}
public void testDispatcherPortletRefresh() throws PortletException {
MockPortletContext portletContext = new MockPortletContext("org/springframework/web/portlet/context");
DispatcherPortlet portlet = new DispatcherPortlet();
portlet.init(new MockPortletConfig(portletContext, "empty"));
PortletContextAwareBean contextBean = (PortletContextAwareBean)
portlet.getPortletApplicationContext().getBean("portletContextAwareBean");
PortletConfigAwareBean configBean = (PortletConfigAwareBean)
portlet.getPortletApplicationContext().getBean("portletConfigAwareBean");
assertSame(portletContext, contextBean.getPortletContext());
assertSame(portlet.getPortletConfig(), configBean.getPortletConfig());
PortletMultipartResolver multipartResolver = portlet.getMultipartResolver();
assertNotNull(multipartResolver);
portlet.refresh();
PortletContextAwareBean contextBean2 = (PortletContextAwareBean)
portlet.getPortletApplicationContext().getBean("portletContextAwareBean");
PortletConfigAwareBean configBean2 = (PortletConfigAwareBean)
portlet.getPortletApplicationContext().getBean("portletConfigAwareBean");
assertSame(portletContext, contextBean.getPortletContext());
assertSame(portlet.getPortletConfig(), configBean.getPortletConfig());
assertTrue(contextBean != contextBean2);
assertTrue(configBean != configBean2);
PortletMultipartResolver multipartResolver2 = portlet.getMultipartResolver();
assertTrue(multipartResolver != multipartResolver2);
portlet.destroy();
}
public void testDispatcherPortletContextRefresh() throws PortletException {
MockPortletContext portletContext = new MockPortletContext("org/springframework/web/portlet/context");
DispatcherPortlet portlet = new DispatcherPortlet();
portlet.init(new MockPortletConfig(portletContext, "empty"));
PortletContextAwareBean contextBean = (PortletContextAwareBean)
portlet.getPortletApplicationContext().getBean("portletContextAwareBean");
PortletConfigAwareBean configBean = (PortletConfigAwareBean)
portlet.getPortletApplicationContext().getBean("portletConfigAwareBean");
assertSame(portletContext, contextBean.getPortletContext());
assertSame(portlet.getPortletConfig(), configBean.getPortletConfig());
PortletMultipartResolver multipartResolver = portlet.getMultipartResolver();
assertNotNull(multipartResolver);
((ConfigurableApplicationContext) portlet.getPortletApplicationContext()).refresh();
PortletContextAwareBean contextBean2 = (PortletContextAwareBean)
portlet.getPortletApplicationContext().getBean("portletContextAwareBean");
PortletConfigAwareBean configBean2 = (PortletConfigAwareBean)
portlet.getPortletApplicationContext().getBean("portletConfigAwareBean");
assertSame(portletContext, contextBean.getPortletContext());
assertSame(portlet.getPortletConfig(), configBean.getPortletConfig());
assertTrue(contextBean != contextBean2);
assertTrue(configBean != configBean2);
PortletMultipartResolver multipartResolver2 = portlet.getMultipartResolver();
assertTrue(multipartResolver != multipartResolver2);
portlet.destroy();
}
}

View File

@@ -0,0 +1,177 @@
/*
* 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.portlet;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
/**
* @author Mark Fisher
*/
public class GenericPortletBeanTests extends TestCase {
public void testInitParameterSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testValue = "testValue";
portletConfig.addInitParameter("testParam", testValue);
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertEquals(testValue, portletBean.getTestParam());
}
public void testInitParameterNotSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
portletBean.init(portletConfig);
assertNull(portletBean.getTestParam());
}
public void testMultipleInitParametersSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testValue = "testValue";
String anotherValue = "anotherValue";
portletConfig.addInitParameter("testParam", testValue);
portletConfig.addInitParameter("anotherParam", anotherValue);
portletConfig.addInitParameter("unknownParam", "unknownValue");
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
assertNull(portletBean.getAnotherParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertNotNull(portletBean.getAnotherParam());
assertEquals(testValue, portletBean.getTestParam());
assertEquals(anotherValue, portletBean.getAnotherParam());
}
public void testMultipleInitParametersOnlyOneSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testValue = "testValue";
portletConfig.addInitParameter("testParam", testValue);
portletConfig.addInitParameter("unknownParam", "unknownValue");
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
assertNull(portletBean.getAnotherParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertEquals(testValue, portletBean.getTestParam());
assertNull(portletBean.getAnotherParam());
}
public void testRequiredInitParameterSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty(testParam);
assertNull(portletBean.getTestParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertEquals(testValue, portletBean.getTestParam());
}
public void testRequiredInitParameterNotSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty(testParam);
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
}
public void testRequiredInitParameterNotSetOtherParameterNotSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty("anotherParam");
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
assertNull(portletBean.getTestParam());
}
public void testUnknownRequiredInitParameter() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty("unknownParam");
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
assertNull(portletBean.getTestParam());
}
private static class TestPortletBean extends GenericPortletBean {
private String testParam;
private String anotherParam;
public void setTestParam(String value) {
this.testParam = value;
}
public String getTestParam() {
return this.testParam;
}
public void setAnotherParam(String value) {
this.anotherParam = value;
}
public String getAnotherParam() {
return this.anotherParam;
}
}
}

View File

@@ -0,0 +1,129 @@
/*
* 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.portlet;
import java.io.IOException;
import java.util.Map;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.ManagedMap;
import org.springframework.validation.BindException;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import org.springframework.web.portlet.handler.ParameterHandlerMapping;
import org.springframework.web.portlet.mvc.SimpleFormController;
/**
* @author Mark Fisher
*/
public class SimplePortletApplicationContext extends StaticPortletApplicationContext {
private String renderCommandSessionAttributeName;
private String formSessionAttributeName;
public void refresh() throws BeansException {
MutablePropertyValues pvs = new MutablePropertyValues();
registerSingleton("controller1", TestFormController.class, pvs);
pvs = new MutablePropertyValues();
pvs.add("bindOnNewForm", "true");
registerSingleton("controller2", TestFormController.class, pvs);
pvs = new MutablePropertyValues();
pvs.add("requireSession", "true");
pvs.add("sessionForm", "true");
pvs.add("bindOnNewForm", "true");
registerSingleton("controller3", TestFormController.class, pvs);
pvs = new MutablePropertyValues();
pvs.add("requireSession", "true");
pvs.add("sessionForm", "true");
pvs.add("bindOnNewForm", "false");
registerSingleton("controller4", TestFormController.class, pvs);
pvs = new MutablePropertyValues();
Map parameterMap = new ManagedMap();
parameterMap.put("form", new RuntimeBeanReference("controller1"));
parameterMap.put("form-bind", new RuntimeBeanReference("controller2"));
parameterMap.put("form-session-bind", new RuntimeBeanReference("controller3"));
parameterMap.put("form-session-nobind", new RuntimeBeanReference("controller4"));
pvs.addPropertyValue(new PropertyValue("parameterMap", parameterMap));
registerSingleton("handlerMapping", ParameterHandlerMapping.class, pvs);
super.refresh();
TestFormController controller1 = (TestFormController) getBean("controller1");
this.renderCommandSessionAttributeName = controller1.getRenderCommandName();
this.formSessionAttributeName = controller1.getFormSessionName();
}
public String getRenderCommandSessionAttributeName() {
return this.renderCommandSessionAttributeName;
}
public String getFormSessionAttributeName() {
return this.formSessionAttributeName;
}
public static class TestFormController extends SimpleFormController {
TestFormController() {
super();
this.setCommandClass(TestBean.class);
this.setCommandName("testBean");
this.setFormView("form");
}
public void doSubmitAction(Object command) {
TestBean testBean = (TestBean) command;
testBean.setAge(testBean.getAge() + 10);
}
public ModelAndView showForm(RenderRequest request, RenderResponse response, BindException errors) throws Exception {
TestBean testBean = (TestBean) errors.getModel().get(getCommandName());
this.writeResponse(response, testBean, false);
return null;
}
public ModelAndView onSubmitRender(RenderRequest request, RenderResponse response, Object command, BindException errors)
throws IOException {
TestBean testBean = (TestBean) command;
this.writeResponse(response, testBean, true);
return null;
}
private String getRenderCommandName() {
return this.getRenderCommandSessionAttributeName();
}
private String getFormSessionName() {
return this.getFormSessionAttributeName();
}
private void writeResponse(RenderResponse response, TestBean testBean, boolean finished) throws IOException {
response.getWriter().write((finished ? "finished" : "") + (testBean.getAge() + 5));
}
}
}

View File

@@ -0,0 +1,237 @@
/*
* 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.portlet.bind;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.core.CollectionFactory;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.validation.BindingResult;
/**
* @author Mark Fisher
*/
public class PortletRequestDataBinderTests extends TestCase {
public void testSimpleBind() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "35");
request.addParameter("name", "test");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertEquals(35, bean.getAge());
assertEquals("test", bean.getName());
}
public void testNestedBind() {
TestBean bean = new TestBean();
bean.setSpouse(new TestBean());
MockPortletRequest request = new MockPortletRequest();
request.addParameter("spouse.name", "test");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSpouse());
assertEquals("test", bean.getSpouse().getName());
}
public void testNestedBindWithPropertyEditor() {
TestBean bean = new TestBean();
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean(text));
}
});
MockPortletRequest request = new MockPortletRequest();
request.addParameter("spouse", "test");
request.addParameter("spouse.age", "32");
binder.bind(request);
assertNotNull(bean.getSpouse());
assertEquals("test", bean.getSpouse().getName());
assertEquals(32, bean.getSpouse().getAge());
}
public void testBindingMismatch() {
TestBean bean = new TestBean();
bean.setAge(30);
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "zzz");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
BindingResult error = binder.getBindingResult();
assertNotNull(error.getFieldError("age"));
assertEquals("typeMismatch", error.getFieldError("age").getCode());
assertEquals(30, bean.getAge());
}
public void testBindingStringWithCommaSeparatedValue() throws Exception {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("stringArray", "test1,test2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getStringArray());
assertEquals(1, bean.getStringArray().length);
assertEquals("test1,test2", bean.getStringArray()[0]);
}
public void testBindingStringArrayWithSplitting() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("stringArray", "test1,test2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.registerCustomEditor(String[].class, new StringArrayPropertyEditor());
binder.bind(request);
assertNotNull(bean.getStringArray());
assertEquals(2, bean.getStringArray().length);
assertEquals("test1", bean.getStringArray()[0]);
assertEquals("test2", bean.getStringArray()[1]);
}
public void testBindingList() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someList[0]", "test1");
request.addParameter("someList[1]", "test2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSomeList());
assertEquals(2, bean.getSomeList().size());
assertEquals("test1", bean.getSomeList().get(0));
assertEquals("test2", bean.getSomeList().get(1));
}
public void testBindingMap() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someMap['key1']", "val1");
request.addParameter("someMap['key2']", "val2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSomeMap());
assertEquals(2, bean.getSomeMap().size());
assertEquals("val1", bean.getSomeMap().get("key1"));
assertEquals("val2", bean.getSomeMap().get("key2"));
}
public void testBindingSet() {
TestBean bean = new TestBean();
Set set = CollectionFactory.createLinkedSetIfPossible(2);
set.add(new TestBean("test1"));
set.add(new TestBean("test2"));
bean.setSomeSet(set);
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someSet[0].age", "35");
request.addParameter("someSet[1].age", "36");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSomeSet());
assertEquals(2, bean.getSomeSet().size());
Iterator iter = bean.getSomeSet().iterator();
TestBean bean1 = (TestBean) iter.next();
assertEquals("test1", bean1.getName());
assertEquals(35, bean1.getAge());
TestBean bean2 = (TestBean) iter.next();
assertEquals("test2", bean2.getName());
assertEquals(36, bean2.getAge());
}
public void testBindingDate() throws Exception {
TestBean bean = new TestBean();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date expected = dateFormat.parse("06-03-2006");
MockPortletRequest request = new MockPortletRequest();
request.addParameter("date", "06-03-2006");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
binder.bind(request);
assertEquals(expected, bean.getDate());
}
public void testBindingFailsWhenMissingRequiredParam() {
TestBean bean = new TestBean();
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.setRequiredFields(new String[] {"age", "name"});
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "35");
binder.bind(request);
BindingResult error = binder.getBindingResult();
assertNotNull(error.getFieldError("name"));
assertEquals("required", error.getFieldError("name").getCode());
}
public void testBindingExcludesDisallowedParam() {
TestBean bean = new TestBean();
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.setAllowedFields(new String[] {"age"});
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "35");
request.addParameter("name", "test");
binder.bind(request);
assertEquals(35, bean.getAge());
assertNull(bean.getName());
}
}

View File

@@ -0,0 +1,64 @@
/*
* 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.portlet.bind;
import org.springframework.mock.web.portlet.MockPortletRequest;
import junit.framework.TestCase;
/**
* @author Mark Fisher
*/
public class PortletRequestParameterPropertyValuesTests extends TestCase {
public void testWithNoParams() {
MockPortletRequest request = new MockPortletRequest();
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request);
assertTrue("Should not have any property values", pvs.getPropertyValues().length == 0);
}
public void testWithNoPrefix() {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param", "value");
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request);
assertEquals("value", pvs.getPropertyValue("param").getValue());
}
public void testWithPrefix() {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("test_param", "value");
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test");
assertTrue(pvs.contains("param"));
assertFalse(pvs.contains("test_param"));
assertEquals("value", pvs.getPropertyValue("param").getValue());
}
public void testWithPrefixAndOverridingSeparator() {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("test.param", "value");
request.addParameter("test_another", "anotherValue");
request.addParameter("some.other", "someValue");
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test", ".");
assertFalse(pvs.contains("test.param"));
assertFalse(pvs.contains("test_another"));
assertFalse(pvs.contains("some.other"));
assertFalse(pvs.contains("another"));
assertFalse(pvs.contains("other"));
assertTrue(pvs.contains("param"));
assertEquals("value", pvs.getPropertyValue("param").getValue());
}
}

View File

@@ -0,0 +1,437 @@
/*
* 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.portlet.bind;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.util.StopWatch;
/**
* @author Juergen Hoeller
* @author Mark Fisher
*/
public class PortletRequestUtilsTests extends TestCase {
public void testIntParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertEquals(PortletRequestUtils.getIntParameter(request, "param1"), new Integer(5));
assertEquals(PortletRequestUtils.getIntParameter(request, "param1", 6), 5);
assertEquals(PortletRequestUtils.getRequiredIntParameter(request, "param1"), 5);
assertEquals(PortletRequestUtils.getIntParameter(request, "param2", 6), 6);
try {
PortletRequestUtils.getRequiredIntParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertEquals(PortletRequestUtils.getIntParameter(request, "param3"), null);
assertEquals(PortletRequestUtils.getIntParameter(request, "param3", 6), 6);
try {
PortletRequestUtils.getRequiredIntParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredIntParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testIntParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
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 = PortletRequestUtils.getRequiredIntParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
try {
PortletRequestUtils.getRequiredIntParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testLongParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertEquals(PortletRequestUtils.getLongParameter(request, "param1"), new Long(5L));
assertEquals(PortletRequestUtils.getLongParameter(request, "param1", 6L), 5L);
assertEquals(PortletRequestUtils.getRequiredIntParameter(request, "param1"), 5L);
assertEquals(PortletRequestUtils.getLongParameter(request, "param2", 6L), 6L);
try {
PortletRequestUtils.getRequiredLongParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertEquals(PortletRequestUtils.getLongParameter(request, "param3"), null);
assertEquals(PortletRequestUtils.getLongParameter(request, "param3", 6L), 6L);
try {
PortletRequestUtils.getRequiredLongParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredLongParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testLongParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
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 = PortletRequestUtils.getRequiredLongParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
try {
PortletRequestUtils.getRequiredLongParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
request.setParameter("param2", new String[] {"1", "2"});
values = PortletRequestUtils.getRequiredLongParameters(request, "param2");
assertEquals(2, values.length);
assertEquals(1, values[0]);
assertEquals(2, values[1]);
}
public void testFloatParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5.5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertTrue(PortletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f)));
assertTrue(PortletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f);
assertTrue(PortletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f);
assertTrue(PortletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f);
try {
PortletRequestUtils.getRequiredFloatParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertTrue(PortletRequestUtils.getFloatParameter(request, "param3") == null);
assertTrue(PortletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f);
try {
PortletRequestUtils.getRequiredFloatParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredFloatParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testFloatParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
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 = PortletRequestUtils.getRequiredFloatParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i], 0);
}
try {
PortletRequestUtils.getRequiredFloatParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testDoubleParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5.5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5)));
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5);
assertTrue(PortletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5);
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5);
try {
PortletRequestUtils.getRequiredDoubleParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param3") == null);
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5);
try {
PortletRequestUtils.getRequiredDoubleParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testDoubleParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
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 = PortletRequestUtils.getRequiredDoubleParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i], 0);
}
try {
PortletRequestUtils.getRequiredDoubleParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testBooleanParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "true");
request.addParameter("param2", "e");
request.addParameter("param4", "yes");
request.addParameter("param5", "1");
request.addParameter("paramEmpty", "");
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE));
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param1", false));
assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param1"));
assertFalse(PortletRequestUtils.getBooleanParameter(request, "param2", true));
assertFalse(PortletRequestUtils.getRequiredBooleanParameter(request, "param2"));
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param3") == null);
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param3", true));
try {
PortletRequestUtils.getRequiredBooleanParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param4", false));
assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param4"));
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param5", false));
assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param5"));
assertFalse(PortletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty"));
}
public void testBooleanParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
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 = PortletRequestUtils.getRequiredBooleanParameters(request, "param");
assertEquals(5, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
array = new boolean[] { false, true, false };
values = PortletRequestUtils.getRequiredBooleanParameters(request, "param2");
assertEquals(array.length, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
}
public void testStringParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "str");
request.addParameter("paramEmpty", "");
assertEquals("str", PortletRequestUtils.getStringParameter(request, "param1"));
assertEquals("str", PortletRequestUtils.getStringParameter(request, "param1", "string"));
assertEquals("str", PortletRequestUtils.getRequiredStringParameter(request, "param1"));
assertEquals(null, PortletRequestUtils.getStringParameter(request, "param3"));
assertEquals("string", PortletRequestUtils.getStringParameter(request, "param3", "string"));
try {
PortletRequestUtils.getRequiredStringParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertEquals("", PortletRequestUtils.getStringParameter(request, "paramEmpty"));
assertEquals("", PortletRequestUtils.getRequiredStringParameter(request, "paramEmpty"));
}
public void testGetIntParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getIntParameter(request, "nonExistingParam", 0);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetLongParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getLongParameter(request, "nonExistingParam", 0);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetFloatParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getFloatParameter(request, "nonExistingParam", 0f);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetDoubleParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getDoubleParameter(request, "nonExistingParam", 0d);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetBooleanParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getBooleanParameter(request, "nonExistingParam", false);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetStringParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.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,142 @@
/*
* 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.portlet.context;
import java.util.Locale;
import javax.servlet.ServletException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.AbstractApplicationContextTests;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.TestListener;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
/**
* Should ideally be eliminated. Copied when splitting .testsuite up into individual bundles.
*
* @see org.springframework.web.context.XmlWebApplicationContextTests
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Chris Beams
*/
public abstract class AbstractXmlWebApplicationContextTests extends AbstractApplicationContextTests {
private ConfigurableWebApplicationContext root;
/**
* Overridden as we can't trust superclass method
* @see org.springframework.context.AbstractApplicationContextTests#testEvents()
*/
public void testEvents() throws Exception {
TestListener listener = (TestListener) this.applicationContext.getBean("testListener");
listener.zeroCounter();
TestListener parentListener = (TestListener) this.applicationContext.getParent().getBean("parentListener");
parentListener.zeroCounter();
parentListener.zeroCounter();
assertTrue("0 events before publication", listener.getEventCount() == 0);
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
this.applicationContext.publishEvent(new MyEvent(this));
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
}
public void testCount() {
assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
this.applicationContext.getBeanDefinitionCount() == 14);
}
public void testContextNesting() {
TestBean father = (TestBean) this.applicationContext.getBean("father");
assertTrue("Bean from root context", father != null);
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
TestBean rod = (TestBean) this.applicationContext.getBean("rod");
assertTrue("Bean from child context", "Rod".equals(rod.getName()));
assertTrue("Bean has external reference", rod.getSpouse() == father);
assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend"));
rod = (TestBean) this.root.getBean("rod");
assertTrue("Bean from root context", "Roderick".equals(rod.getName()));
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
}
public void testInitializingBeanAndInitMethod() throws Exception {
assertFalse(InitAndIB.constructed);
InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib");
assertTrue(InitAndIB.constructed);
assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked);
assertTrue(!iib.destroyed && !iib.customDestroyed);
this.applicationContext.close();
assertTrue(!iib.destroyed && !iib.customDestroyed);
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) this.applicationContext.getParent();
parent.close();
assertTrue(iib.destroyed && iib.customDestroyed);
parent.close();
assertTrue(iib.destroyed && iib.customDestroyed);
}
public static class InitAndIB implements InitializingBean, DisposableBean {
public static boolean constructed;
public boolean afterPropertiesSetInvoked, initMethodInvoked, destroyed, customDestroyed;
public InitAndIB() {
constructed = true;
}
public void afterPropertiesSet() {
if (this.initMethodInvoked)
fail();
this.afterPropertiesSetInvoked = true;
}
/** Init method */
public void customInit() throws ServletException {
if (!this.afterPropertiesSetInvoked)
fail();
this.initMethodInvoked = true;
}
public void destroy() {
if (this.customDestroyed)
fail();
if (this.destroyed) {
throw new IllegalStateException("Already destroyed");
}
this.destroyed = true;
}
public void customDestroy() {
if (!this.destroyed)
fail();
if (this.customDestroyed) {
throw new IllegalStateException("Already customDestroyed");
}
this.customDestroyed = true;
}
}
}

View File

@@ -0,0 +1,128 @@
/*
* 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.portlet.context;
import javax.portlet.PortletContext;
import javax.portlet.PortletSession;
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.MockServletContext;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.ServletWrappingPortletContext;
import org.springframework.web.context.ContextCleanupListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.support.GenericWebApplicationContext;
/**
* @author Juergen Hoeller
*/
public class PortletApplicationContextScopeTests {
private static final String NAME = "scoped";
private ConfigurablePortletApplicationContext initApplicationContext(String scope) {
MockServletContext sc = new MockServletContext();
GenericWebApplicationContext rac = new GenericWebApplicationContext(sc);
rac.refresh();
PortletContext pc = new ServletWrappingPortletContext(sc);
StaticPortletApplicationContext ac = new StaticPortletApplicationContext();
ac.setParent(rac);
ac.setPortletContext(pc);
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);
MockRenderRequest request = new MockRenderRequest();
PortletRequestAttributes requestAttributes = new PortletRequestAttributes(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);
MockRenderRequest request = new MockRenderRequest();
PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getPortletSession().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getPortletSession().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
request.getPortletSession().invalidate();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testGlobalSessionScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_GLOBAL_SESSION);
MockRenderRequest request = new MockRenderRequest();
PortletRequestAttributes requestAttributes = new PortletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getPortletSession().getAttribute(NAME, PortletSession.APPLICATION_SCOPE));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getPortletSession().getAttribute(NAME, PortletSession.APPLICATION_SCOPE));
assertSame(bean, ac.getBean(NAME));
request.getPortletSession().invalidate();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testApplicationScope() {
ConfigurablePortletApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION);
assertNull(ac.getPortletContext().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, ac.getPortletContext().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext()));
assertTrue(bean.wasDestroyed());
}
}

View File

@@ -0,0 +1,35 @@
/*
* 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.portlet.context;
import javax.portlet.PortletConfig;
/**
* @author Mark Fisher
*/
public class PortletConfigAwareBean implements PortletConfigAware {
private PortletConfig portletConfig;
public void setPortletConfig(PortletConfig portletConfig) {
this.portletConfig = portletConfig;
}
public PortletConfig getPortletConfig() {
return portletConfig;
}
}

View File

@@ -0,0 +1,35 @@
/*
* 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.portlet.context;
import javax.portlet.PortletContext;
/**
* @author Mark Fisher
*/
public class PortletContextAwareBean implements PortletContextAware {
private PortletContext portletContext;
public void setPortletContext(PortletContext portletContext) {
this.portletContext = portletContext;
}
public PortletContext getPortletContext() {
return portletContext;
}
}

View File

@@ -0,0 +1,154 @@
/*
* 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.portlet.context;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
/**
* @author Mark Fisher
*/
public class PortletContextAwareProcessorTests extends TestCase {
public void testPortletContextAwareWithPortletContext() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithPortletContextAndPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithNullPortletContextAndNonNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithNonNullPortletContextAndNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithNullPortletContext() {
PortletContext portletContext = null;
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletContext());
}
public void testPortletConfigAwareWithPortletContextOnly() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletConfig());
}
public void testPortletConfigAwareWithPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletConfig should have been set", bean.getPortletConfig());
assertEquals(portletConfig, bean.getPortletConfig());
}
public void testPortletConfigAwareWithPortletContextAndPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletConfig should have been set", bean.getPortletConfig());
assertEquals(portletConfig, bean.getPortletConfig());
}
public void testPortletConfigAwareWithNullPortletContextAndNonNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletConfig should have been set", bean.getPortletConfig());
assertEquals(portletConfig, bean.getPortletConfig());
}
public void testPortletConfigAwareWithNonNullPortletContextAndNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletConfig());
}
public void testPortletConfigAwareWithNullPortletContext() {
PortletContext portletContext = null;
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletConfig());
}
}

View File

@@ -0,0 +1,174 @@
/*
* 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.portlet.context;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
import java.io.Serializable;
import javax.portlet.PortletRequest;
import org.junit.Test;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.mock.web.portlet.MockPortletSession;
import org.springframework.web.context.request.RequestAttributes;
/**
* @author Rick Evans
* @author Juergen Hoeller
* @author Chris Beams
*/
public class PortletRequestAttributesTests {
private static final String KEY = "ThatThingThatThing";
@SuppressWarnings("serial")
private static final Serializable VALUE = new Serializable() { };
@Test(expected=IllegalArgumentException.class)
public void testCtorRejectsNullArg() throws Exception {
new PortletRequestAttributes(null);
}
@Test
public void testUpdateAccessedAttributes() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute(KEY, VALUE);
MockPortletRequest request = new MockPortletRequest();
request.setSession(session);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
assertSame(VALUE, value);
attrs.requestCompleted();
}
@Test
public void testSetRequestScopedAttribute() throws Exception {
MockPortletRequest request = new MockPortletRequest();
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
Object value = request.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void testSetRequestScopedAttributeAfterCompletion() throws Exception {
MockPortletRequest request = new MockPortletRequest();
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
request.close();
try {
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_REQUEST);
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
@Test
public void testSetSessionScopedAttribute() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute(KEY, VALUE);
MockPortletRequest request = new MockPortletRequest();
request.setSession(session);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void testSetSessionScopedAttributeAfterCompletion() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute(KEY, VALUE);
MockPortletRequest request = new MockPortletRequest();
request.setSession(session);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.requestCompleted();
request.close();
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void testSetGlobalSessionScopedAttribute() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute(KEY, VALUE);
MockPortletRequest request = new MockPortletRequest();
request.setSession(session);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void testSetGlobalSessionScopedAttributeAfterCompletion() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute(KEY, VALUE);
MockPortletRequest request = new MockPortletRequest();
request.setSession(session);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.requestCompleted();
request.close();
attrs.setAttribute(KEY, VALUE, RequestAttributes.SCOPE_GLOBAL_SESSION);
Object value = session.getAttribute(KEY);
assertSame(VALUE, value);
}
@Test
public void testGetSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(null);
replay(request);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
assertNull(value);
verify(request);
}
@Test
public void testRemoveSessionScopedAttribute() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute(KEY, VALUE);
MockPortletRequest request = new MockPortletRequest();
request.setSession(session);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
Object value = session.getAttribute(KEY);
assertNull(value);
}
@Test
public void testRemoveSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(null);
replay(request);
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
verify(request);
}
}

View File

@@ -0,0 +1,114 @@
/*
* 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.portlet.context;
import java.util.Locale;
import java.util.Map;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.PortletResponse;
import javax.portlet.filter.PortletRequestWrapper;
import javax.portlet.filter.PortletResponseWrapper;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.mock.web.portlet.MockPortletResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.multipart.MultipartRequest;
/**
* @author Juergen Hoeller
* @since 26.07.2006
*/
public class PortletWebRequestTests {
@Test
public void testParameters() {
MockPortletRequest portletRequest = new MockPortletRequest();
portletRequest.addParameter("param1", "value1");
portletRequest.addParameter("param2", "value2");
portletRequest.addParameter("param2", "value2a");
PortletWebRequest request = new PortletWebRequest(portletRequest);
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 testLocale() {
MockPortletRequest portletRequest = new MockPortletRequest();
portletRequest.addPreferredLocale(Locale.UK);
PortletWebRequest request = new PortletWebRequest(portletRequest);
assertEquals(Locale.UK, request.getLocale());
}
@Test
public void testNativeRequest() {
MockRenderRequest portletRequest = new MockRenderRequest();
MockRenderResponse portletResponse = new MockRenderResponse();
PortletWebRequest request = new PortletWebRequest(portletRequest, portletResponse);
assertSame(portletRequest, request.getNativeRequest());
assertSame(portletRequest, request.getNativeRequest(PortletRequest.class));
assertSame(portletRequest, request.getNativeRequest(RenderRequest.class));
assertSame(portletRequest, request.getNativeRequest(MockRenderRequest.class));
assertNull(request.getNativeRequest(MultipartRequest.class));
assertSame(portletResponse, request.getNativeResponse());
assertSame(portletResponse, request.getNativeResponse(PortletResponse.class));
assertSame(portletResponse, request.getNativeResponse(RenderResponse.class));
assertSame(portletResponse, request.getNativeResponse(MockRenderResponse.class));
assertNull(request.getNativeResponse(MultipartRequest.class));
}
@Test
public void testDecoratedNativeRequest() {
MockRenderRequest portletRequest = new MockRenderRequest();
MockRenderResponse portletResponse = new MockRenderResponse();
PortletRequest decoratedRequest = new PortletRequestWrapper(portletRequest);
PortletResponse decoratedResponse = new PortletResponseWrapper(portletResponse);
PortletWebRequest request = new PortletWebRequest(decoratedRequest, decoratedResponse);
assertSame(decoratedRequest, request.getNativeRequest());
assertSame(decoratedRequest, request.getNativeRequest(PortletRequest.class));
assertSame(portletRequest, request.getNativeRequest(RenderRequest.class));
assertSame(portletRequest, request.getNativeRequest(MockRenderRequest.class));
assertNull(request.getNativeRequest(MultipartRequest.class));
assertSame(decoratedResponse, request.getNativeResponse());
assertSame(decoratedResponse, request.getNativeResponse(PortletResponse.class));
assertSame(portletResponse, request.getNativeResponse(RenderResponse.class));
assertSame(portletResponse, request.getNativeResponse(MockRenderResponse.class));
assertNull(request.getNativeResponse(MultipartRequest.class));
}
}

View File

@@ -0,0 +1,81 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd" [
<!ENTITY contextInclude SYSTEM "org/springframework/web/portlet/context/WEB-INF/contextInclude.xml">
]>
<beans>
<import resource="resources/messageSource.xml"/>
<import resource="/resources/../resources/themeSource.xml"/>
<bean id="lifecyclePostProcessor" class="org.springframework.beans.factory.LifecycleBean$PostProcessor"/>
<!--
<bean
name="performanceMonitor" class="org.springframework.context.support.TestListener"
/>
-->
<!--
<bean name="aca" class="org.springframework.context.ACATest">
</bean>
<bean name="aca-prototype" class="org.springframework.context.ACATest" scope="prototype">
</bean>
-->
<bean id="beanThatListens" class="org.springframework.context.BeanThatListens"/>
<bean id="parentListener" class="org.springframework.context.TestListener"/>
<!-- Inherited tests -->
<!-- name and age values will be overridden by myinit.properties" -->
<bean id="rod" class="org.springframework.beans.TestBean">
<property name="name">
<value>dummy</value>
</property>
<property name="age">
<value>-1</value>
</property>
</bean>
<!--
Tests of lifecycle callbacks
-->
<bean id="mustBeInitialized"
class="org.springframework.beans.factory.MustBeInitialized">
</bean>
<bean id="lifecycle"
class="org.springframework.context.LifecycleContextBean"
init-method="declaredInitMethod">
<property name="initMethodDeclared"><value>true</value></property>
</bean>
&contextInclude;
<bean id="myOverride" class="org.springframework.beans.factory.config.PropertyOverrideConfigurer">
<property name="location">
<value>/org/springframework/web/portlet/context/WEB-INF/myoverride.properties</value>
</property>
</bean>
<bean id="myPlaceholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/org/springframework/web/portlet/context/WEB-INF/myplace*.properties</value>
<value>classpath:/org/springframework/web/portlet/context/WEB-INF/myover*.properties</value>
</list>
</property>
</bean>
<bean id="init-and-ib"
class="org.springframework.web.portlet.context.AbstractXmlWebApplicationContextTests$InitAndIB"
lazy-init="true"
init-method="customInit"
destroy-method="customDestroy"
/>
</beans>

View File

@@ -0,0 +1,6 @@
code1=message1
code2=message2
# Example taken from the javadocs for the java.text.MessageFormat class
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
message.format.example2=This is a test message in the message catalog with no args.

View File

@@ -0,0 +1,2 @@
# Example taken from the javadocs for the java.text.MessageFormat class
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on station number {0,number,integer}.

View File

@@ -0,0 +1,5 @@
code1=message1
# Example taken from the javadocs for the java.text.MessageFormat class
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
message.format.example2=This is a test message in the message catalog with no args.

View File

@@ -0,0 +1,6 @@
<!-- Include snippet to be loaded via entity reference in applicationContext.xml -->
<bean id="father" class="org.springframework.beans.TestBean">
<property name="name"><value>yetanotherdummy</value></property>
</bean>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="portletMultipartResolver" class="org.springframework.web.portlet.multipart.CommonsPortletMultipartResolver"/>
<bean id="portletContextAwareBean" class="org.springframework.web.portlet.context.PortletContextAwareBean"/>
<bean id="portletConfigAwareBean" class="org.springframework.web.portlet.context.PortletConfigAwareBean"/>
</beans>

View File

@@ -0,0 +1,3 @@
father.name=Albert
rod.age=31
rod.name=Roderick

View File

@@ -0,0 +1,4 @@
useCodeAsDefaultMessage=false
message-file=context-messages
objectName=test:service=myservice
theme-base=org/springframework/web/portlet/context/WEB-INF/

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="useCodeAsDefaultMessage">
<value>${useCodeAsDefaultMessage}</value>
</property>
<property name="basenames">
<list>
<value>org/springframework/web/portlet/context/WEB-INF/${message-file}</value>
<value>org/springframework/web/portlet/context/WEB-INF/more-context-messages</value>
</list>
</property>
</bean>
<bean id="messageSourceString" factory-bean="messageSource" factory-method="toString"/>
<bean id="currentTimeMillis" class="javax.management.ObjectName" factory-method="getInstance">
<constructor-arg value="${objectName}"/>
</bean>
</beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
<property name="basenamePrefix">
<value>${theme-base}</value>
</property>
</bean>
</beans>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<import resource="classpath:/org/springframework/web/portlet/context/WEB-INF/test-servlet.xml"/>
<bean id="portletContextAwareBean" class="org.springframework.web.portlet.context.PortletContextAwareBean"/>
<bean id="portletConfigAwareBean" class="org.springframework.web.portlet.context.PortletConfigAwareBean"/>
</beans>

View File

@@ -0,0 +1,59 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basename"><value>org/springframework/web/context/WEB-INF/test-messages</value></property>
</bean>
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
<property name="basenamePrefix"><value>org/springframework/web/context/WEB-INF/test-</value></property>
</bean>
<bean id="aca" class="org.springframework.context.ACATester"/>
<bean id="aca-prototype" class="org.springframework.context.ACATester" scope="prototype"/>
<bean id="rod" class="org.springframework.beans.TestBean">
<property name="name"><value>Rod</value></property>
<property name="age"><value>31</value></property>
<property name="spouse"><ref bean="father"/></property>
</bean>
<bean id="testListener" class="org.springframework.context.TestListener"/>
<bean id="roderick" parent="rod">
<property name="name"><value>Roderick</value></property>
<property name="age"><value>31</value></property>
</bean>
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype"/>
<bean id="kerry" class="org.springframework.beans.TestBean">
<property name="name"><value>Kerry</value></property>
<property name="age"><value>34</value></property>
<property name="spouse"><ref local="rod"/></property>
</bean>
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
<property name="name"><value>typeMismatch</value></property>
<property name="age"><value>34x</value></property>
<property name="spouse"><ref local="rod"/></property>
</bean>
<bean id="singletonFactory" class="org.springframework.beans.factory.DummyFactory">
</bean>
<bean id="prototypeFactory" class="org.springframework.beans.factory.DummyFactory">
<property name="singleton"><value>false</value></property>
</bean>
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
<property name="name"><value>listenerVeto</value></property>
<property name="age"><value>66</value></property>
</bean>
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
</beans>

View File

@@ -0,0 +1,134 @@
/*
* 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.portlet.context;
import java.util.Locale;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Mark Fisher
* @author Chris Beams
*/
public class XmlPortletApplicationContextTests extends AbstractXmlWebApplicationContextTests {
private ConfigurablePortletApplicationContext root;
protected ConfigurableApplicationContext createContext() throws Exception {
root = new XmlPortletApplicationContext();
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
root.setPortletConfig(portletConfig);
root.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml"});
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof TestBean) {
((TestBean) bean).getFriends().add("myFriend");
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
});
}
});
root.refresh();
XmlPortletApplicationContext pac = new XmlPortletApplicationContext();
pac.setParent(root);
pac.setPortletConfig(portletConfig);
pac.setNamespace("test-portlet");
pac.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml"});
pac.refresh();
return pac;
}
/**
* Overridden in order to use MockPortletConfig
* @see org.springframework.web.context.XmlWebApplicationContextTests#testWithoutMessageSource()
*/
public void testWithoutMessageSource() throws Exception {
MockPortletContext portletContext = new MockPortletContext("");
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
XmlPortletApplicationContext pac = new XmlPortletApplicationContext();
pac.setParent(root);
pac.setPortletConfig(portletConfig);
pac.setNamespace("testNamespace");
pac.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml"});
pac.refresh();
try {
pac.getMessage("someMessage", null, Locale.getDefault());
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected;
}
String msg = pac.getMessage("someMessage", null, "default", Locale.getDefault());
assertTrue("Default message returned", "default".equals(msg));
}
/**
* Overridden in order to access the root ApplicationContext
* @see org.springframework.web.context.XmlWebApplicationContextTests#testContextNesting()
*/
public void testContextNesting() {
TestBean father = (TestBean) this.applicationContext.getBean("father");
assertTrue("Bean from root context", father != null);
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
TestBean rod = (TestBean) this.applicationContext.getBean("rod");
assertTrue("Bean from child context", "Rod".equals(rod.getName()));
assertTrue("Bean has external reference", rod.getSpouse() == father);
assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend"));
rod = (TestBean) this.root.getBean("rod");
assertTrue("Bean from root context", "Roderick".equals(rod.getName()));
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
}
public void testCount() {
assertTrue("should have 16 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
this.applicationContext.getBeanDefinitionCount() == 16);
}
public void testPortletContextAwareBean() {
PortletContextAwareBean bean = (PortletContextAwareBean)this.applicationContext.getBean("portletContextAwareBean");
assertNotNull(bean.getPortletContext());
}
public void testPortletConfigAwareBean() {
PortletConfigAwareBean bean = (PortletConfigAwareBean)this.applicationContext.getBean("portletConfigAwareBean");
assertNotNull(bean.getPortletConfig());
}
}

View File

@@ -0,0 +1,103 @@
/*
* 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.portlet.handler;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.web.portlet.HandlerMapping;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class ParameterHandlerMappingTests extends TestCase {
public static final String CONF = "/org/springframework/web/portlet/handler/parameterMapping.xml";
private ConfigurablePortletApplicationContext pac;
public void setUp() throws Exception {
MockPortletContext portletContext = new MockPortletContext();
pac = new XmlPortletApplicationContext();
pac.setPortletContext(portletContext);
pac.setConfigLocations(new String[] {CONF});
pac.refresh();
}
public void testParameterMapping() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest addRequest = new MockPortletRequest();
addRequest.addParameter("action", "add");
MockPortletRequest removeRequest = new MockPortletRequest();
removeRequest.addParameter("action", "remove");
Object addHandler = hm.getHandler(addRequest).getHandler();
Object removeHandler = hm.getHandler(removeRequest).getHandler();
assertEquals(pac.getBean("addItemHandler"), addHandler);
assertEquals(pac.getBean("removeItemHandler"), removeHandler);
}
public void testUnregisteredHandlerWithNoDefault() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.addParameter("action", "modify");
assertNull(hm.getHandler(request));
}
public void testUnregisteredHandlerWithDefault() throws Exception {
ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping");
Object defaultHandler = new Object();
hm.setDefaultHandler(defaultHandler);
MockPortletRequest request = new MockPortletRequest();
request.addParameter("action", "modify");
assertNotNull(hm.getHandler(request));
assertEquals(defaultHandler, hm.getHandler(request).getHandler());
}
public void testConfiguredParameterName() throws Exception {
ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping");
hm.setParameterName("someParam");
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someParam", "add");
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("addItemHandler"), handler);
}
public void testDuplicateMappingAttempt() {
ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler("add", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
}

View File

@@ -0,0 +1,131 @@
/*
* 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.portlet.handler;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
/**
* @author Mark Fisher
*/
public class ParameterMappingInterceptorTests extends TestCase {
public void testDefaultParameterMapped() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME;
String value = "someValue";
request.setParameter(param, value);
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandleAction(request, response, handler);
assertTrue(shouldProceed);
assertNotNull(response.getRenderParameter(param));
assertEquals(value, response.getRenderParameter(param));
}
public void testNonDefaultParameterNotMapped() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = "myParam";
String value = "someValue";
request.setParameter(param, value);
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME));
}
public void testNonDefaultParameterMappedWhenHandlerMappingProvided() throws Exception {
String param = "myParam";
String value = "someValue";
ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping();
handlerMapping.setParameterName(param);
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
interceptor.setParameterName(param);
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter(param, value);
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandleAction(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME));
assertNotNull(response.getRenderParameter(param));
assertEquals(value, response.getRenderParameter(param));
}
public void testNoEffectForRenderRequest() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME;
String value = "someValue";
request.setParameter(param, value);
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
}
public void testNoParameterValueSetWithDefaultParameterName() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME;
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
}
public void testNoParameterValueSetWithNonDefaultParameterName() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = "myParam";
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
}
public void testNoParameterValueSetWithNonDefaultParameterNameWhenHandlerMappingProvided() throws Exception {
String param = "myParam";
ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping();
handlerMapping.setParameterName(param);
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
interceptor.setParameterName(param);
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
}
}

View File

@@ -0,0 +1,87 @@
/*
* 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.portlet.handler;
import javax.portlet.PortletMode;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.web.portlet.HandlerMapping;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class PortletModeHandlerMappingTests extends TestCase {
public static final String CONF = "/org/springframework/web/portlet/handler/portletModeMapping.xml";
private ConfigurablePortletApplicationContext pac;
public void setUp() throws Exception {
MockPortletContext portletContext = new MockPortletContext();
pac = new XmlPortletApplicationContext();
pac.setPortletContext(portletContext);
pac.setConfigLocations(new String[] {CONF});
pac.refresh();
}
public void testPortletModeView() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.VIEW);
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("viewHandler"), handler);
}
public void testPortletModeEdit() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.EDIT);
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("editHandler"), handler);
}
public void testPortletModeHelp() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.HELP);
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("helpHandler"), handler);
}
public void testDuplicateMappingAttempt() {
PortletModeHandlerMapping hm = (PortletModeHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler(PortletMode.VIEW, new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
}

View File

@@ -0,0 +1,112 @@
/*
* 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.portlet.handler;
import javax.portlet.PortletMode;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.web.portlet.HandlerMapping;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class PortletModeParameterHandlerMappingTests extends TestCase {
public static final String CONF = "/org/springframework/web/portlet/handler/portletModeParameterMapping.xml";
private ConfigurablePortletApplicationContext pac;
public void setUp() throws Exception {
MockPortletContext portletContext = new MockPortletContext();
pac = new XmlPortletApplicationContext();
pac.setPortletContext(portletContext);
pac.setConfigLocations(new String[] {CONF});
pac.refresh();
}
public void testPortletModeViewWithParameter() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest addRequest = new MockPortletRequest();
addRequest.setPortletMode(PortletMode.VIEW);
addRequest.setParameter("action", "add");
MockPortletRequest removeRequest = new MockPortletRequest();
removeRequest.setPortletMode(PortletMode.VIEW);
removeRequest.setParameter("action", "remove");
Object addHandler = hm.getHandler(addRequest).getHandler();
Object removeHandler = hm.getHandler(removeRequest).getHandler();
assertEquals(pac.getBean("addItemHandler"), addHandler);
assertEquals(pac.getBean("removeItemHandler"), removeHandler);
}
public void testPortletModeEditWithParameter() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.EDIT);
request.setParameter("action", "prefs");
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("preferencesHandler"), handler);
}
public void testDuplicateMappingInSamePortletMode() {
PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler(PortletMode.VIEW, "remove", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
public void testDuplicateMappingInDifferentPortletMode() {
PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler(PortletMode.EDIT, "remove", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
public void testAllowDuplicateMappingInDifferentPortletMode() throws Exception {
PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping");
hm.setAllowDuplicateParameters(true);
Object editRemoveHandler = new Object();
hm.registerHandler(PortletMode.EDIT, "remove", editRemoveHandler);
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.EDIT);
request.setParameter("action", "remove");
Object handler = hm.getHandler(request).getHandler();
assertEquals(editRemoveHandler, handler);
}
}

View File

@@ -0,0 +1,277 @@
/*
* 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.portlet.handler;
import java.util.Collections;
import java.util.Properties;
import javax.portlet.WindowState;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* @author Seth Ladd
* @author Mark Fisher
* @author Juergen Hoeller
*/
public class SimpleMappingExceptionResolverTests extends TestCase {
private static final String DEFAULT_VIEW = "default-view";
private SimpleMappingExceptionResolver exceptionResolver;
private MockRenderRequest request;
private MockRenderResponse response;
private Object handler1;
private Object handler2;
private Exception genericException;
protected void setUp() {
exceptionResolver = new SimpleMappingExceptionResolver();
request = new MockRenderRequest();
response = new MockRenderResponse();
handler1 = new String();
handler2 = new Object();
genericException = new Exception();
}
public void testSetOrder() {
exceptionResolver.setOrder(2);
assertEquals(2, exceptionResolver.getOrder());
}
public void testDefaultErrorView() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals(DEFAULT_VIEW, mav.getViewName());
assertEquals(genericException, mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE));
}
public void testDefaultErrorViewDifferentHandler() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testDefaultErrorViewDifferentHandlerClass() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setMappedHandlerClasses(new Class[] {String.class});
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testNullDefaultErrorView() {
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNull("No default error view set - ModelAndView should be null", mav);
}
public void testNullExceptionAttribute() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setExceptionAttribute(null);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals(DEFAULT_VIEW, mav.getViewName());
assertNull(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE));
}
public void testNullExceptionMappings() {
exceptionResolver.setExceptionMappings(null);
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals(DEFAULT_VIEW, mav.getViewName());
}
public void testDefaultNoRenderWhenMinimized() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
request.setWindowState(WindowState.MINIMIZED);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNull("Should not render when WindowState is MINIMIZED", mav);
}
public void testDoRenderWhenMinimized() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setRenderWhenMinimized(true);
request.setWindowState(WindowState.MINIMIZED);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNotNull("ModelAndView should not be null", mav);
assertEquals(DEFAULT_VIEW, mav.getViewName());
}
public void testSimpleExceptionMapping() {
Properties props = new Properties();
props.setProperty("Exception", "error");
exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION");
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testExactExceptionMappingWithHandlerSpecified() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testExactExceptionMappingWithHandlerClassSpecified() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
exceptionResolver.setMappedHandlerClasses(new Class[] {String.class});
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testExactExceptionMappingWithHandlerInterfaceSpecified() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
exceptionResolver.setMappedHandlerClasses(new Class[] {Comparable.class});
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testSimpleExceptionMappingWithHandlerSpecifiedButWrongHandler() {
Properties props = new Properties();
props.setProperty("Exception", "error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testSimpleExceptionMappingWithHandlerSpecifiedButWrongHandlerClass() {
Properties props = new Properties();
props.setProperty("Exception", "error");
exceptionResolver.setMappedHandlerClasses(new Class[] {String.class});
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testMissingExceptionInMapping() {
Properties props = new Properties();
props.setProperty("SomeFooThrowable", "error");
exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION");
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNull("Exception not mapped - ModelAndView should be null", mav);
}
public void testTwoMappings() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("AnotherException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testTwoMappingsOneShortOneLong() {
Properties props = new Properties();
props.setProperty("Exception", "error");
props.setProperty("AnotherException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testTwoMappingsOneShortOneLongThrowOddException() {
Exception oddException = new SomeOddException();
Properties props = new Properties();
props.setProperty("Exception", "error");
props.setProperty("SomeOddException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("error", mav.getViewName());
}
public void testTwoMappingsThrowOddExceptionUseLongExceptionMapping() {
Exception oddException = new SomeOddException();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("another-error", mav.getViewName());
}
public void testThreeMappings() {
Exception oddException = new AnotherOddException();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "another-error");
props.setProperty("AnotherOddException", "another-some-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("another-some-error", mav.getViewName());
}
public void testExceptionWithSubstringMatchingParent() {
Exception oddException = new SomeOddExceptionChild();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "parent-error");
props.setProperty("SomeOddExceptionChild", "child-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("child-error", mav.getViewName());
}
public void testMostSpecificExceptionInHierarchyWins() {
Exception oddException = new NoSubstringMatchesThisException();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "parent-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("parent-error", mav.getViewName());
}
private static class SomeOddException extends Exception {
}
private static class SomeOddExceptionChild extends SomeOddException {
}
private static class NoSubstringMatchesThisException extends SomeOddException {
}
private static class AnotherOddException extends Exception {
}
}

View File

@@ -0,0 +1,110 @@
/*
* 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.portlet.handler;
import javax.portlet.PortletSecurityException;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
/**
* @author Mark Fisher
*/
public class UserRoleAuthorizationInterceptorTests extends TestCase {
public void testAuthorizedUser() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole = "allowed";
interceptor.setAuthorizedRoles(new String[] {validRole});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole(validRole);
assertTrue(request.isUserInRole(validRole));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
}
public void testAuthorizedUserWithMultipleRoles() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole1 = "allowed1";
String validRole2 = "allowed2";
interceptor.setAuthorizedRoles(new String[] {validRole1, validRole2});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole(validRole2);
request.addUserRole("someOtherRole");
assertFalse(request.isUserInRole(validRole1));
assertTrue(request.isUserInRole(validRole2));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
}
public void testUnauthorizedUser() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole = "allowed";
interceptor.setAuthorizedRoles(new String[] {validRole});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole("someOtherRole");
assertFalse(request.isUserInRole(validRole));
try {
interceptor.preHandle(request, response, handler);
fail("should have thrown PortletSecurityException");
}
catch (PortletSecurityException ex) {
// expected
}
}
public void testRequestWithNoUserRoles() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole = "allowed";
interceptor.setAuthorizedRoles(new String[] {validRole});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
assertFalse(request.isUserInRole(validRole));
try {
interceptor.preHandle(request, response, handler);
fail("should have thrown PortletSecurityException");
}
catch (PortletSecurityException ex) {
// expected
}
}
public void testInterceptorWithNoAuthorizedRoles() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole("someRole");
try {
interceptor.preHandle(request, response, handler);
fail("should have thrown PortletSecurityException");
}
catch (PortletSecurityException ex) {
// expected
}
}
}

View File

@@ -0,0 +1,19 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="handlerMapping" class="org.springframework.web.portlet.handler.ParameterHandlerMapping">
<property name="parameterMap">
<map>
<entry key="add" value-ref="addItemHandler"/>
<entry key="remove" value-ref="removeItemHandler"/>
</map>
</property>
</bean>
<bean id="addItemHandler" class="java.lang.Object"/>
<bean id="removeItemHandler" class="java.lang.Object"/>
</beans>

View File

@@ -0,0 +1,22 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="handlerMapping" class="org.springframework.web.portlet.handler.PortletModeHandlerMapping">
<property name="portletModeMap">
<map>
<entry key="view" value-ref="viewHandler"/>
<entry key="edit" value-ref="editHandler"/>
<entry key="help" value-ref="helpHandler"/>
</map>
</property>
</bean>
<bean id="viewHandler" class="java.lang.Object"/>
<bean id="editHandler" class="java.lang.Object"/>
<bean id="helpHandler" class="java.lang.Object"/>
</beans>

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
<beans>
<bean id="handlerMapping" class="org.springframework.web.portlet.handler.PortletModeParameterHandlerMapping">
<property name="portletModeParameterMap">
<map>
<entry key="view">
<map>
<entry key="add" value-ref="addItemHandler"/>
<entry key="remove" value-ref="removeItemHandler"/>
</map>
</entry>
<entry key="edit">
<map>
<entry key="prefs" value-ref="preferencesHandler"/>
</map>
</entry>
</map>
</property>
</bean>
<bean id="addItemHandler" class="java.lang.Object"/>
<bean id="removeItemHandler" class="java.lang.Object"/>
<bean id="preferencesHandler" class="java.lang.Object"/>
</beans>

View File

@@ -0,0 +1,461 @@
/*
* 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.portlet.mvc;
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.handler.PortletSessionRequiredException;
/**
* @author Mark Fisher
*/
public class CommandControllerTests extends TestCase {
private static final String ERRORS_KEY = "errors";
public void testRenderRequestWithNoParams() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
assertNotNull(mav.getModel().get(tc.getCommandName()));
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertNotNull(errors);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testRenderRequestWithParams() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals("Name should be bound", name, command.getName());
assertEquals("Age should be bound", age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertNotNull(errors);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testRenderRequestWithMismatch() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
request.addParameter("name", name);
request.addParameter("age", "zzz");
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertNotNull(command);
assertEquals("Name should be bound", name, command.getName());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
assertNotNull(errors.getFieldError("age"));
assertEquals("typeMismatch", errors.getFieldError("age").getCode());
}
public void testRenderWhenMinimizedReturnsNull() throws Exception {
TestController tc = new TestController();
assertFalse(tc.isRenderWhenMinimized());
MockRenderRequest request = new MockRenderRequest();
request.setWindowState(WindowState.MINIMIZED);
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
assertNull("ModelAndView should be null", mav);
}
public void testAllowRenderWhenMinimized() throws Exception {
TestController tc = new TestController();
tc.setRenderWhenMinimized(true);
MockRenderRequest request = new MockRenderRequest();
request.setWindowState(WindowState.MINIMIZED);
request.setContextPath("test");
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
assertNotNull("ModelAndView should not be null", mav);
assertEquals("test-view", mav.getViewName());
assertNotNull(mav.getModel().get(tc.getCommandName()));
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testRequiresSessionWithoutSession() throws Exception {
TestController tc = new TestController();
tc.setRequireSession(true);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
try {
tc.handleRenderRequest(request, response);
fail("Should have thrown PortletSessionRequiredException");
}
catch (PortletSessionRequiredException ex) {
// expected
}
}
public void testRequiresSessionWithSession() throws Exception {
TestController tc = new TestController();
tc.setRequireSession(true);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
// create the session
request.getPortletSession(true);
try {
tc.handleRenderRequest(request, response);
}
catch (PortletSessionRequiredException ex) {
fail("Should not have thrown PortletSessionRequiredException");
}
}
public void testRenderRequestWithoutCacheSetting() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertNull("Expiration-cache should be null", cacheProperty);
}
public void testRenderRequestWithNegativeCacheSetting() throws Exception {
TestController tc = new TestController();
tc.setCacheSeconds(-99);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertNull("Expiration-cache should be null", cacheProperty);
}
public void testRenderRequestWithZeroCacheSetting() throws Exception {
TestController tc = new TestController();
tc.setCacheSeconds(0);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertEquals("Expiration-cache should be set to 0 seconds", "0", cacheProperty);
}
public void testRenderRequestWithPositiveCacheSetting() throws Exception {
TestController tc = new TestController();
tc.setCacheSeconds(30);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertEquals("Expiration-cache should be set to 30 seconds", "30", cacheProperty);
}
public void testActionRequest() throws Exception {
TestController tc = new TestController();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
tc.handleActionRequest(request, response);
TestBean command = (TestBean)request.getPortletSession().getAttribute(tc.getRenderCommandSessionAttributeName());
assertTrue(command.isJedi());
}
public void testSuppressBinding() throws Exception {
TestController tc = new TestController() {
protected boolean suppressBinding(PortletRequest request) {
return true;
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertNotNull(command);
assertTrue("Name should not have been bound", name != command.getName());
assertTrue("Age should not have been bound", age != command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testWithCustomDateEditor() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
String dateString = "07-03-2006";
Date expectedDate = dateFormat.parse(dateString);
request.addParameter("date", dateString);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
assertEquals(expectedDate, command.getDate());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testWithCustomDateEditorEmptyNotAllowed() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
String emptyString = "";
request.addParameter("date", emptyString);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
assertNotNull(errors.getFieldError("date"));
assertEquals("typeMismatch", errors.getFieldError("date").getCode());
assertEquals(emptyString, errors.getFieldError("date").getRejectedValue());
}
public void testWithCustomDateEditorEmptyAllowed() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
String dateString = "";
request.addParameter("date", dateString);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 0 errors", 0, errors.getErrorCount());
assertNull("date should be null", command.getDate());
}
public void testNestedBindingWithPropertyEditor() throws Exception {
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean(text));
}
});
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
String spouseName = "testSpouse";
int age = 30;
int spouseAge = 31;
request.addParameter("name", name);
request.addParameter("age", "" + age);
request.addParameter("spouse", spouseName);
request.addParameter("spouse.age", "" + spouseAge);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
assertNotNull(command.getSpouse());
assertEquals(spouseName, command.getSpouse().getName());
assertEquals(spouseAge, command.getSpouse().getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testWithValidatorNotSupportingCommandClass() throws Exception {
Validator v = new Validator() {
public boolean supports(Class c) {
return false;
}
public void validate(Object o, Errors e) {}
};
TestController tc = new TestController();
tc.setValidator(v);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
try {
tc.handleRenderRequest(request, response);
fail("Should have thrown IllegalArgumentException");
}
catch(IllegalArgumentException e) {
// expected
}
}
public void testWithValidatorAddingGlobalError() throws Exception {
final String errorCode = "someCode";
final String defaultMessage = "validation error!";
TestController tc = new TestController();
tc.setValidator(new Validator() {
public boolean supports(Class c) {
return TestBean.class.isAssignableFrom(c);
}
public void validate(Object o, Errors e) {
e.reject(errorCode, defaultMessage);
}
});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
ObjectError error = errors.getGlobalError();
assertEquals(error.getCode(), errorCode);
assertEquals(error.getDefaultMessage(), defaultMessage);
}
public void testWithValidatorAndNullFieldError() throws Exception {
final String errorCode = "someCode";
final String defaultMessage = "validation error!";
TestController tc = new TestController();
tc.setValidator(new Validator() {
public boolean supports(Class c) {
return TestBean.class.isAssignableFrom(c);
}
public void validate(Object o, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", errorCode, defaultMessage);
}
});
MockRenderRequest request = new MockRenderRequest();
int age = 32;
request.setParameter("age", "" + age);
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertNull("name should be null", command.getName());
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
FieldError error = errors.getFieldError("name");
assertEquals(error.getCode(), errorCode);
assertEquals(error.getDefaultMessage(), defaultMessage);
}
public void testWithValidatorAndWhitespaceFieldError() throws Exception {
final String errorCode = "someCode";
final String defaultMessage = "validation error!";
TestController tc = new TestController();
tc.setValidator(new Validator() {
public boolean supports(Class c) {
return TestBean.class.isAssignableFrom(c);
}
public void validate(Object o, Errors e) {
ValidationUtils.rejectIfEmptyOrWhitespace(e, "name", errorCode, defaultMessage);
}
});
MockRenderRequest request = new MockRenderRequest();
int age = 32;
String whitespace = " \t ";
request.setParameter("age", "" + age);
request.setParameter("name", whitespace);
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertTrue(command.getName().equals(whitespace));
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
FieldError error = errors.getFieldError("name");
assertEquals("rejected value should contain whitespace", whitespace, error.getRejectedValue());
assertEquals(error.getCode(), errorCode);
assertEquals(error.getDefaultMessage(), defaultMessage);
}
private static class TestController extends AbstractCommandController {
private TestController() {
super(TestBean.class, "testBean");
}
protected void handleAction(ActionRequest request, ActionResponse response, Object command, BindException errors) {
((TestBean)command).setJedi(true);
}
protected ModelAndView handleRender(RenderRequest request, RenderResponse response, Object command, BindException errors) {
assertNotNull(command);
assertNotNull(errors);
Map model = new HashMap();
model.put(getCommandName(), command);
model.put(ERRORS_KEY, errors);
return new ModelAndView(request.getContextPath() + "-view", model);
}
}
}

View File

@@ -0,0 +1,73 @@
/*
* 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.portlet.mvc;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class ParameterizableViewControllerTests extends TestCase {
public void testRenderRequestWithViewNameSet() throws Exception {
ParameterizableViewController controller = new ParameterizableViewController();
String viewName = "testView";
controller.setViewName(viewName);
RenderRequest request = new MockRenderRequest();
RenderResponse response = new MockRenderResponse();
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals(viewName, mav.getViewName());
}
public void testInitApplicationContextWithNoViewNameSet() throws Exception {
ParameterizableViewController controller = new ParameterizableViewController();
try {
controller.setApplicationContext(new StaticPortletApplicationContext());
fail("should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testActionRequestNotHandled() throws Exception {
ParameterizableViewController controller = new ParameterizableViewController();
ActionRequest request = new MockActionRequest();
ActionResponse response = new MockActionResponse();
try {
controller.handleActionRequest(request, response);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
}
}

View File

@@ -0,0 +1,76 @@
/*
* 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.portlet.mvc;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* @author Mark Fisher
*/
public class PortletModeNameViewControllerTests extends TestCase {
private PortletModeNameViewController controller;
public void setUp() {
controller = new PortletModeNameViewController();
}
public void testEditPortletMode() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.EDIT);
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals("edit", mav.getViewName());
}
public void testHelpPortletMode() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.HELP);
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals("help", mav.getViewName());
}
public void testViewPortletMode() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals("view", mav.getViewName());
}
public void testActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
try {
controller.handleActionRequest(request, response);
fail("Should have thrown PortletException");
}
catch(PortletException ex) {
// expected
}
}
}

View File

@@ -0,0 +1,196 @@
/*
* 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.portlet.mvc;
import static org.junit.Assert.assertEquals;
import java.io.IOException;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.Portlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import org.junit.Before;
import org.junit.Test;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
/**
* Unit tests for the {@link PortletWrappingController} class.
*
* @author Mark Fisher
* @author Rick Evans
* @author Chris Beams
*/
public final class PortletWrappingControllerTests {
private static final String RESULT_RENDER_PARAMETER_NAME = "result";
private static final String PORTLET_WRAPPING_CONTROLLER_BEAN_NAME = "controller";
private static final String RENDERED_RESPONSE_CONTENT = "myPortlet-view";
private static final String PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME = "portletName";
private PortletWrappingController controller;
@Before
public void setUp() {
ConfigurablePortletApplicationContext applicationContext = new MyApplicationContext();
MockPortletConfig config = new MockPortletConfig(new MockPortletContext(), "wrappedPortlet");
applicationContext.setPortletConfig(config);
applicationContext.refresh();
controller = (PortletWrappingController) applicationContext.getBean(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME);
}
@Test
public void testActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter("test", "test");
controller.handleActionRequest(request, response);
String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME);
assertEquals("myPortlet-action", result);
}
@Test
public void testRenderRequest() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
controller.handleRenderRequest(request, response);
String result = response.getContentAsString();
assertEquals(RENDERED_RESPONSE_CONTENT, result);
}
@Test(expected=IllegalArgumentException.class)
public void testActionRequestWithNoParameters() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
controller.handleActionRequest(request, response);
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsPortletClassThatDoesNotImplementPortletInterface() throws Exception {
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(String.class);
controller.afterPropertiesSet();
}
@Test(expected=IllegalArgumentException.class)
public void testRejectsIfPortletClassIsNotSupplied() throws Exception {
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(null);
controller.afterPropertiesSet();
}
@Test(expected=IllegalStateException.class)
public void testDestroyingTheControllerPropagatesDestroyToWrappedPortlet() throws Exception {
final PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(MyPortlet.class);
controller.afterPropertiesSet();
// test for destroy() call being propagated via exception being thrown :(
controller.destroy();
}
@Test
public void testPortletName() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "test");
controller.handleActionRequest(request, response);
String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME);
assertEquals("wrappedPortlet", result);
}
@Test
public void testDelegationToMockPortletConfigIfSoConfigured() throws Exception {
final String BEAN_NAME = "Sixpence None The Richer";
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(MyPortlet.class);
controller.setUseSharedPortletConfig(false);
controller.setBeanName(BEAN_NAME);
controller.afterPropertiesSet();
request.setParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME, "true");
controller.handleActionRequest(request, response);
String result = response.getRenderParameter(RESULT_RENDER_PARAMETER_NAME);
assertEquals(BEAN_NAME, result);
}
public static final class MyPortlet implements Portlet {
private PortletConfig portletConfig;
public void init(PortletConfig portletConfig) {
this.portletConfig = portletConfig;
}
public void processAction(ActionRequest request, ActionResponse response) throws PortletException {
if (request.getParameter("test") != null) {
response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, "myPortlet-action");
} else if (request.getParameter(PORTLET_NAME_ACTION_REQUEST_PARAMETER_NAME) != null) {
response.setRenderParameter(RESULT_RENDER_PARAMETER_NAME, getPortletConfig().getPortletName());
} else {
throw new IllegalArgumentException("no request parameters");
}
}
public void render(RenderRequest request, RenderResponse response) throws IOException {
response.getWriter().write(RENDERED_RESPONSE_CONTENT);
}
public PortletConfig getPortletConfig() {
return this.portletConfig;
}
public void destroy() {
throw new IllegalStateException("Being destroyed...");
}
}
private static final class MyApplicationContext extends StaticPortletApplicationContext {
public void refresh() throws BeansException {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("portletClass", MyPortlet.class);
registerSingleton(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME, PortletWrappingController.class, pvs);
super.refresh();
}
}
}

View File

@@ -0,0 +1,156 @@
/*
* 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.portlet.mvc.annotation;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.BindException;
import java.net.SocketException;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.util.ClassUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.portlet.ModelAndView;
/**
* @author Arjen Poutsma
* @author Juergen Hoeller
*/
public class AnnotationMethodHandlerExceptionResolverTests {
private AnnotationMethodHandlerExceptionResolver exceptionResolver;
private MockRenderRequest request;
private MockRenderResponse response;
@Before
public void setUp() {
exceptionResolver = new AnnotationMethodHandlerExceptionResolver();
request = new MockRenderRequest();
response = new MockRenderResponse();
}
@Test
public void simpleWithIOException() {
IOException ex = new IOException();
SimpleController controller = new SimpleController();
ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex);
assertNotNull("No ModelAndView returned", mav);
assertEquals("Invalid view name returned", "X:IOException", mav.getViewName());
}
@Test
public void simpleWithSocketException() {
SocketException ex = new SocketException();
SimpleController controller = new SimpleController();
ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex);
assertNotNull("No ModelAndView returned", mav);
assertEquals("Invalid view name returned", "Y:SocketException", mav.getViewName());
}
@Test
public void simpleWithFileNotFoundException() {
FileNotFoundException ex = new FileNotFoundException();
SimpleController controller = new SimpleController();
ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex);
assertNotNull("No ModelAndView returned", mav);
assertEquals("Invalid view name returned", "X:FileNotFoundException", mav.getViewName());
}
@Test
public void simpleWithBindException() {
BindException ex = new BindException();
SimpleController controller = new SimpleController();
ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex);
assertNotNull("No ModelAndView returned", mav);
assertEquals("Invalid view name returned", "Y:BindException", mav.getViewName());
}
@Test
public void inherited() {
IOException ex = new IOException();
InheritedController controller = new InheritedController();
ModelAndView mav = exceptionResolver.resolveException(request, response, controller, ex);
assertNotNull("No ModelAndView returned", mav);
assertEquals("Invalid view name returned", "GenericError", mav.getViewName());
}
@Test(expected = IllegalStateException.class)
public void ambiguous() {
IllegalArgumentException ex = new IllegalArgumentException();
AmbiguousController controller = new AmbiguousController();
exceptionResolver.resolveException(request, response, controller, ex);
}
@Controller
private static class SimpleController {
@ExceptionHandler(IOException.class)
public String handleIOException(IOException ex, PortletRequest request) {
return "X:" + ClassUtils.getShortName(ex.getClass());
}
@ExceptionHandler(SocketException.class)
public String handleSocketException(Exception ex, PortletResponse response) {
return "Y:" + ClassUtils.getShortName(ex.getClass());
}
@ExceptionHandler(IllegalArgumentException.class)
public String handleIllegalArgumentException(Exception ex) {
return ClassUtils.getShortName(ex.getClass());
}
}
@Controller
private static class InheritedController extends SimpleController {
@Override
public String handleIOException(IOException ex, PortletRequest request) {
return "GenericError";
}
}
@Controller
private static class AmbiguousController {
@ExceptionHandler({BindException.class, IllegalArgumentException.class})
public String handle1(Exception ex, PortletRequest request, PortletResponse response) {
return ClassUtils.getShortName(ex.getClass());
}
@ExceptionHandler
public String handle2(IllegalArgumentException ex) {
return ClassUtils.getShortName(ex.getClass());
}
}
}

View File

@@ -0,0 +1,832 @@
/*
* 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.portlet.mvc.annotation;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.MimeResponse;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.springframework.beans.BeansException;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigUtils;
import org.springframework.core.MethodParameter;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ExtendedModelMap;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.bind.support.WebBindingInitializer;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.portlet.DispatcherPortlet;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.NoHandlerFoundException;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import org.springframework.web.portlet.mvc.AbstractController;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.mvc.annotation.ModelAndViewResolver;
/**
* @author Juergen Hoeller
* @since 2.5
*/
public class PortletAnnotationControllerTests extends TestCase {
public void testStandardHandleMethod() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyController.class));
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test", response.getContentAsString());
}
public void testAdaptedHandleMethods() throws Exception {
doTestAdaptedHandleMethods(MyAdaptedController.class);
}
public void testAdaptedHandleMethods2() throws Exception {
doTestAdaptedHandleMethods(MyAdaptedController2.class);
}
public void testAdaptedHandleMethods3() throws Exception {
doTestAdaptedHandleMethods(MyAdaptedController3.class);
}
public void doTestAdaptedHandleMethods(final Class controllerClass) throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(controllerClass));
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockActionRequest actionRequest = new MockActionRequest(PortletMode.VIEW);
MockActionResponse actionResponse = new MockActionResponse();
portlet.processAction(actionRequest, actionResponse);
assertEquals("value", actionResponse.getRenderParameter("test"));
MockRenderRequest request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("param1", "value1");
request.addParameter("param2", "2");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test-value1-2", response.getContentAsString());
request = new MockRenderRequest(PortletMode.HELP);
request.addParameter("name", "name1");
request.addParameter("age", "2");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test-name1-2", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("name", "name1");
request.addParameter("age", "value2");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("test-name1-typeMismatch", response.getContentAsString());
}
public void testFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("name", "name1");
request.addParameter("age", "value2");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString());
}
public void testModelFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyModelFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("name", "name1");
request.addParameter("age", "value2");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-name1-typeMismatch-tb1-myValue", response.getContentAsString());
}
public void testCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyCommandProvidingFormController.class));
RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer());
wac.registerBeanDefinition("handlerAdapter", adapterDef);
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("defaultName", "myDefaultName");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testTypedCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyTypedCommandProvidingFormController.class));
wac.registerBeanDefinition("controller2", new RootBeanDefinition(MyOtherTypedCommandProvidingFormController.class));
RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
adapterDef.getPropertyValues().add("webBindingInitializer", new MyWebBindingInitializer());
adapterDef.getPropertyValues().add("customArgumentResolver", new MySpecialArgumentResolver());
wac.registerBeanDefinition("handlerAdapter", adapterDef);
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("myParam", "myValue");
request.addParameter("defaultName", "10");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("myParam", "myOtherValue");
request.addParameter("defaultName", "10");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherView-Integer:10-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("defaultName", "10");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-myName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testBinderInitializingCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MyBinderInitializingCommandProvidingFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("defaultName", "myDefaultName");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testSpecificBinderInitializingCommandProvidingFormController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.registerBeanDefinition("controller", new RootBeanDefinition(MySpecificBinderInitializingCommandProvidingFormController.class));
wac.refresh();
return wac;
}
protected void render(ModelAndView mv, PortletRequest request, MimeResponse response) throws Exception {
new TestView().render(mv.getViewName(), mv.getModel(), request, response);
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("defaultName", "myDefaultName");
request.addParameter("age", "value2");
request.addParameter("date", "2007-10-02");
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView-String:myDefaultName-typeMismatch-tb1-myOriginalValue", response.getContentAsString());
}
public void testParameterDispatchingController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.setPortletContext(new MockPortletContext());
RootBeanDefinition bd = new RootBeanDefinition(MyParameterDispatchingController.class);
bd.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller", bd);
AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("view", "other");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("view", "my");
request.addParameter("lang", "de");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLangView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
request.addParameter("surprise", "!");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("mySurpriseView", response.getContentAsString());
}
public void testTypeLevelParameterDispatchingController() throws Exception {
DispatcherPortlet portlet = new DispatcherPortlet() {
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
StaticPortletApplicationContext wac = new StaticPortletApplicationContext();
wac.setPortletContext(new MockPortletContext());
RootBeanDefinition bd = new RootBeanDefinition(MyTypeLevelParameterDispatchingController.class);
bd.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller", bd);
RootBeanDefinition bd2 = new RootBeanDefinition(MySpecialParameterDispatchingController.class);
bd2.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller2", bd2);
RootBeanDefinition bd3 = new RootBeanDefinition(MyOtherSpecialParameterDispatchingController.class);
bd3.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller3", bd3);
RootBeanDefinition bd4 = new RootBeanDefinition(MyParameterDispatchingController.class);
bd4.setScope(WebApplicationContext.SCOPE_REQUEST);
wac.registerBeanDefinition("controller4", bd4);
AnnotationConfigUtils.registerAnnotationConfigProcessors(wac);
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.HELP);
MockRenderResponse response = new MockRenderResponse();
try {
portlet.render(request, response);
fail("Should have thrown NoHandlerFoundException");
}
catch (NoHandlerFoundException ex) {
// expected
}
request = new MockRenderRequest(PortletMode.EDIT);
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myDefaultView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "mySpecialValue");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("mySpecialView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myOtherSpecialValue");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherSpecialView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.VIEW);
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("view", "other");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myOtherView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("view", "my");
request.addParameter("lang", "de");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("myLangView", response.getContentAsString());
request = new MockRenderRequest(PortletMode.EDIT);
request.addParameter("myParam", "myValue");
request.addParameter("surprise", "!");
response = new MockRenderResponse();
portlet.render(request, response);
assertEquals("mySurpriseView", response.getContentAsString());
}
public void testMavResolver() throws Exception {
@SuppressWarnings("serial") DispatcherPortlet portlet = new DispatcherPortlet() {
@Override
protected ApplicationContext createPortletApplicationContext(ApplicationContext parent) throws BeansException {
GenericWebApplicationContext wac = new GenericWebApplicationContext();
wac.registerBeanDefinition("controller",
new RootBeanDefinition(ModelAndViewResolverController.class));
RootBeanDefinition adapterDef = new RootBeanDefinition(AnnotationMethodHandlerAdapter.class);
adapterDef.getPropertyValues()
.add("customModelAndViewResolver", new MyModelAndViewResolver());
wac.registerBeanDefinition("handlerAdapter", adapterDef);
wac.refresh();
return wac;
}
};
portlet.init(new MockPortletConfig());
MockRenderRequest request = new MockRenderRequest(PortletMode.VIEW);
MockRenderResponse response = new MockRenderResponse();
portlet.render(request, response);
}
@RequestMapping("VIEW")
private static class MyController extends AbstractController {
protected ModelAndView handleRenderRequestInternal(RenderRequest request, RenderResponse response) throws Exception {
response.getWriter().write("test");
return null;
}
}
@Controller
private static class MyAdaptedController {
@RequestMapping("VIEW")
public void myHandle(ActionRequest request, ActionResponse response) throws IOException {
response.setRenderParameter("test", "value");
}
@RequestMapping("EDIT")
public void myHandle(@RequestParam("param1")String p1, @RequestParam("param2")int p2, RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2);
}
@RequestMapping("HELP")
public void myHandle(TestBean tb, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge());
}
@RequestMapping("VIEW")
public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
}
@Controller
private static class MyAdaptedController2 {
@RequestMapping("VIEW")
public void myHandle(ActionRequest request, ActionResponse response) throws IOException {
response.setRenderParameter("test", "value");
}
@RequestMapping("EDIT")
public void myHandle(@RequestParam("param1")String p1, int param2, RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + param2);
}
@RequestMapping("HELP")
public void myHandle(TestBean tb, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge());
}
@RequestMapping("VIEW")
public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
}
@Controller
@RequestMapping({"VIEW", "EDIT", "HELP"})
private static class MyAdaptedController3 {
@RequestMapping
public void myHandle(ActionRequest request, ActionResponse response) {
response.setRenderParameter("test", "value");
}
@RequestMapping("EDIT")
public void myHandle(@RequestParam("param1")String p1, @RequestParam("param2")int p2, RenderResponse response) throws IOException {
response.getWriter().write("test-" + p1 + "-" + p2);
}
@RequestMapping("HELP")
public void myHandle(TestBean tb, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + tb.getAge());
}
@RequestMapping
public void myHandle(TestBean tb, Errors errors, RenderResponse response) throws IOException {
response.getWriter().write("test-" + tb.getName() + "-" + errors.getFieldError("age").getCode());
}
}
@Controller
private static class MyFormController {
@ModelAttribute("testBeanList")
public List<TestBean> getTestBeans() {
List<TestBean> list = new LinkedList<TestBean>();
list.add(new TestBean("tb1"));
list.add(new TestBean("tb2"));
return list;
}
@RequestMapping("VIEW")
public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
}
@Controller
private static class MyModelFormController {
@ModelAttribute
public List<TestBean> getTestBeans() {
List<TestBean> list = new LinkedList<TestBean>();
list.add(new TestBean("tb1"));
list.add(new TestBean("tb2"));
return list;
}
@RequestMapping("VIEW")
public String myHandle(@ModelAttribute("myCommand")TestBean tb, BindingResult errors, Model model) {
if (!model.containsAttribute("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
}
@Controller
private static class MyCommandProvidingFormController<T, TB, TB2> extends MyFormController {
@ModelAttribute("myCommand")
private TestBean createTestBean(
@RequestParam T defaultName, Map<String, Object> model, @RequestParam Date date) {
model.put("myKey", "myOriginalValue");
return new TestBean(defaultName.getClass().getSimpleName() + ":" + defaultName.toString());
}
@RequestMapping("VIEW")
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
@RequestMapping("EDIT")
public String myOtherHandle(TB tb, BindingResult errors, ExtendedModelMap model, MySpecialArg arg) {
TestBean tbReal = (TestBean) tb;
tbReal.setName("myName");
assertTrue(model.get("ITestBean") instanceof DerivedTestBean);
assertNotNull(arg);
return super.myHandle(tbReal, errors, model);
}
@ModelAttribute
protected TB2 getModelAttr() {
return (TB2) new DerivedTestBean();
}
}
private static class MySpecialArg {
public MySpecialArg(String value) {
}
}
@Controller
@RequestMapping(params = "myParam=myValue")
private static class MyTypedCommandProvidingFormController
extends MyCommandProvidingFormController<Integer, TestBean, ITestBean> {
}
@Controller
@RequestMapping(params = "myParam=myOtherValue")
private static class MyOtherTypedCommandProvidingFormController
extends MyCommandProvidingFormController<Integer, TestBean, ITestBean> {
@RequestMapping("VIEW")
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myOtherView";
}
}
@Controller
private static class MyBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController {
@InitBinder
private void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
@Controller
private static class MySpecificBinderInitializingCommandProvidingFormController extends MyCommandProvidingFormController {
@SuppressWarnings("unused")
@InitBinder({"myCommand", "date"})
private void initBinder(WebDataBinder binder) {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
private static class MyWebBindingInitializer implements WebBindingInitializer {
public void initBinder(WebDataBinder binder, WebRequest request) {
assertNotNull(request.getLocale());
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
dateFormat.setLenient(false);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
}
private static class MySpecialArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
if (methodParameter.getParameterType().equals(MySpecialArg.class)) {
return new MySpecialArg("myValue");
}
return UNRESOLVED;
}
}
@Controller
@RequestMapping("VIEW")
private static class MyParameterDispatchingController {
@Autowired
private PortletContext portletContext;
@Autowired
private PortletSession session;
@Autowired
private PortletRequest request;
@RequestMapping
public void myHandle(RenderResponse response) throws IOException {
if (this.portletContext == null || this.session == null || this.request == null) {
throw new IllegalStateException();
}
response.getWriter().write("myView");
}
@RequestMapping(params = {"view", "!lang"})
public void myOtherHandle(RenderResponse response) throws IOException {
response.getWriter().write("myOtherView");
}
@RequestMapping(params = {"view=my", "lang=de"})
public void myLangHandle(RenderResponse response) throws IOException {
response.getWriter().write("myLangView");
}
@RequestMapping(params = "surprise")
public void mySurpriseHandle(RenderResponse response) throws IOException {
response.getWriter().write("mySurpriseView");
}
}
@Controller
@RequestMapping(value = "EDIT", params = "myParam=myValue")
private static class MyTypeLevelParameterDispatchingController extends MyParameterDispatchingController {
}
@Controller
@RequestMapping("EDIT")
private static class MySpecialParameterDispatchingController {
@RequestMapping(params = "myParam=mySpecialValue")
public void myHandle(RenderResponse response) throws IOException {
response.getWriter().write("mySpecialView");
}
@RequestMapping
public void myDefaultHandle(RenderResponse response) throws IOException {
response.getWriter().write("myDefaultView");
}
}
@Controller
@RequestMapping("EDIT")
private static class MyOtherSpecialParameterDispatchingController {
@RequestMapping(params = "myParam=myOtherSpecialValue")
public void myHandle(RenderResponse response) throws IOException {
response.getWriter().write("myOtherSpecialView");
}
}
private static class TestView {
public void render(String viewName, Map model, PortletRequest request, MimeResponse response) throws Exception {
TestBean tb = (TestBean) model.get("testBean");
if (tb == null) {
tb = (TestBean) model.get("myCommand");
}
if (tb.getName().endsWith("myDefaultName")) {
assertTrue(tb.getDate().getYear() == 107);
}
Errors errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "testBean");
if (errors == null) {
errors = (Errors) model.get(BindingResult.MODEL_KEY_PREFIX + "myCommand");
}
if (errors.hasFieldErrors("date")) {
throw new IllegalStateException();
}
List<TestBean> testBeans = (List<TestBean>) model.get("testBeanList");
response.getWriter().write(viewName + "-" + tb.getName() + "-" + errors.getFieldError("age").getCode() +
"-" + testBeans.get(0).getName() + "-" + model.get("myKey"));
}
}
@Controller
public static class ModelAndViewResolverController {
@RequestMapping("VIEW")
public MySpecialArg handle() {
return new MySpecialArg("foo");
}
}
public static class MyModelAndViewResolver implements ModelAndViewResolver {
public org.springframework.web.servlet.ModelAndView resolveModelAndView(Method handlerMethod,
Class handlerType,
Object returnValue,
ExtendedModelMap implicitModel,
NativeWebRequest webRequest) {
if (returnValue instanceof MySpecialArg) {
return new org.springframework.web.servlet.ModelAndView(new View() {
public String getContentType() {
return "text/html";
}
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
response.getWriter().write("myValue");
}
});
}
return UNRESOLVED;
}
}
}

View File

@@ -0,0 +1,538 @@
/*
* Copyright 2002-20011 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.portlet.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletSession;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.mock.web.portlet.MockPortletSession;
import org.springframework.web.util.WebUtils;
import static org.easymock.EasyMock.*;
import static org.junit.Assert.*;
/**
* @author Rick Evans
* @author Chris Beams
*/
public final class PortletUtilsTests {
@Test(expected=IllegalArgumentException.class)
public void testGetTempDirWithNullPortletContext() throws Exception {
PortletUtils.getTempDir(null);
}
public void testGetTempDirSunnyDay() throws Exception {
MockPortletContext ctx = new MockPortletContext();
Object expectedTempDir = new File("doesn't exist but that's ok in the context of this test");
ctx.setAttribute(WebUtils.TEMP_DIR_CONTEXT_ATTRIBUTE, expectedTempDir);
assertSame(expectedTempDir, PortletUtils.getTempDir(ctx));
}
public void testGetRealPathInterpretsLocationAsRelativeToWebAppRootIfPathDoesNotBeginWithALeadingSlash() throws Exception {
final String originalPath = "web/foo";
final String expectedRealPath = "/" + originalPath;
PortletContext ctx = createMock(PortletContext.class);
expect(ctx.getRealPath(expectedRealPath)).andReturn(expectedRealPath);
replay(ctx);
String actualRealPath = PortletUtils.getRealPath(ctx, originalPath);
assertEquals(expectedRealPath, actualRealPath);
verify(ctx);
}
@Test(expected=IllegalArgumentException.class)
public void testGetRealPathWithNullPortletContext() throws Exception {
PortletUtils.getRealPath(null, "/foo");
}
@Test(expected=NullPointerException.class)
public void testGetRealPathWithNullPath() throws Exception {
PortletUtils.getRealPath(new MockPortletContext(), null);
}
@Test(expected=FileNotFoundException.class)
public void testGetRealPathWithPathThatCannotBeResolvedToFile() throws Exception {
PortletUtils.getRealPath(new MockPortletContext() {
public String getRealPath(String path) {
return null;
}
}, "/rubbish");
}
@Test
public void testPassAllParametersToRenderPhase() throws Exception {
MockActionRequest request = new MockActionRequest();
request.setParameter("William", "Baskerville");
request.setParameter("Adso", "Melk");
MockActionResponse response = new MockActionResponse();
PortletUtils.passAllParametersToRenderPhase(request, response);
assertEquals("The render parameters map is obviously not being populated with the request parameters.",
request.getParameterMap().size(), response.getRenderParameterMap().size());
}
@Test
public void testGetParametersStartingWith() throws Exception {
final String targetPrefix = "francisan_";
final String badKey = "dominican_Bernard";
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetPrefix + "William", "Baskerville");
request.setParameter(targetPrefix + "Adso", "Melk");
request.setParameter(badKey, "Gui");
Map<?, ?> actualParameters = PortletUtils.getParametersStartingWith(request, targetPrefix);
assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters);
assertEquals("Obviously not finding all of the correct parameters", 2, actualParameters.size());
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William"));
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso"));
assertFalse("Obviously not finding all of the correct parameters (is returning a parameter whose name does not start with the desired prefix",
actualParameters.containsKey(badKey));
}
@Test
public void testGetParametersStartingWithUnpicksScalarParameterValues() throws Exception {
final String targetPrefix = "francisan_";
final String badKey = "dominican_Bernard";
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetPrefix + "William", "Baskerville");
request.setParameter(targetPrefix + "Adso", new String[]{"Melk", "Of Melk"});
request.setParameter(badKey, "Gui");
Map<?, ?> actualParameters = PortletUtils.getParametersStartingWith(request, targetPrefix);
assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters);
assertEquals("Obviously not finding all of the correct parameters", 2, actualParameters.size());
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William"));
assertEquals("Not picking scalar parameter value out correctly",
"Baskerville", actualParameters.get("William"));
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso"));
assertFalse("Obviously not finding all of the correct parameters (is returning a parameter whose name does not start with the desired prefix",
actualParameters.containsKey(badKey));
}
@Test
public void testGetParametersStartingWithYieldsEverythingIfTargetPrefixIsNull() throws Exception {
MockPortletRequest request = new MockPortletRequest();
request.setParameter("William", "Baskerville");
request.setParameter("Adso", "Melk");
request.setParameter("dominican_Bernard", "Gui");
Map<?, ?> actualParameters = PortletUtils.getParametersStartingWith(request, null);
assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters);
assertEquals("Obviously not finding all of the correct parameters", request.getParameterMap().size(), actualParameters.size());
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William"));
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso"));
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("dominican_Bernard"));
}
@Test
public void testGetParametersStartingWithYieldsEverythingIfTargetPrefixIsTheEmptyString() throws Exception {
MockPortletRequest request = new MockPortletRequest();
request.setParameter("William", "Baskerville");
request.setParameter("Adso", "Melk");
request.setParameter("dominican_Bernard", "Gui");
Map<?, ?> actualParameters = PortletUtils.getParametersStartingWith(request, "");
assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters);
assertEquals("Obviously not finding all of the correct parameters", request.getParameterMap().size(), actualParameters.size());
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("William"));
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("Adso"));
assertTrue("Obviously not finding all of the correct parameters", actualParameters.containsKey("dominican_Bernard"));
}
@Test
public void testGetParametersStartingWithYieldsEmptyNonNullMapWhenNoParamaterExistInRequest() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map<?, ?> actualParameters = PortletUtils.getParametersStartingWith(request, null);
assertNotNull("PortletUtils.getParametersStartingWith(..) must never return a null Map", actualParameters);
assertEquals("Obviously finding some parameters from somewhere (incorrectly)",
request.getParameterMap().size(), actualParameters.size());
}
@Test
public void testGetSubmitParameterWithStraightNameMatch() throws Exception {
final String targetSubmitParameter = "William";
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetSubmitParameter, "Baskerville");
request.setParameter("Adso", "Melk");
request.setParameter("dominican_Bernard", "Gui");
String submitParameter = PortletUtils.getSubmitParameter(request, targetSubmitParameter);
assertNotNull(submitParameter);
assertEquals(targetSubmitParameter, submitParameter);
}
@Test
public void testGetSubmitParameterWithPrefixedParameterMatch() throws Exception {
final String bareParameterName = "William";
final String targetParameterName = bareParameterName + WebUtils.SUBMIT_IMAGE_SUFFIXES[0];
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetParameterName, "Baskerville");
request.setParameter("Adso", "Melk");
String submitParameter = PortletUtils.getSubmitParameter(request, bareParameterName);
assertNotNull(submitParameter);
assertEquals(targetParameterName, submitParameter);
}
@Test
public void testGetSubmitParameterWithNoParameterMatchJustReturnsNull() throws Exception {
MockPortletRequest request = new MockPortletRequest();
request.setParameter("Bill", "Baskerville");
request.setParameter("Adso", "Melk");
String submitParameter = PortletUtils.getSubmitParameter(request, "William");
assertNull(submitParameter);
}
@Test(expected=IllegalArgumentException.class)
public void testGetSubmitParameterWithNullRequest() throws Exception {
final String targetSubmitParameter = "William";
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetSubmitParameter, "Baskerville");
request.setParameter("Adso", "Melk");
PortletUtils.getSubmitParameter(null, targetSubmitParameter);
}
@Test
public void testPassAllParametersToRenderPhaseDoesNotPropagateExceptionIfRedirectAlreadySentAtTimeOfCall() throws Exception {
MockActionRequest request = new MockActionRequest();
request.setParameter("William", "Baskerville");
request.setParameter("Adso", "Melk");
MockActionResponse response = new MockActionResponse() {
public void setRenderParameter(String key, String[] values) {
throw new IllegalStateException();
}
};
PortletUtils.passAllParametersToRenderPhase(request, response);
assertEquals("The render parameters map must not be being populated with the request parameters (Action.sendRedirect(..) aleady called).",
0, response.getRenderParameterMap().size());
}
@Test
public void testClearAllRenderParameters() throws Exception {
MockActionResponse response = new MockActionResponse();
response.setRenderParameter("William", "Baskerville");
response.setRenderParameter("Adso", "Melk");
PortletUtils.clearAllRenderParameters(response);
assertEquals("The render parameters map is obviously not being cleared out.",
0, response.getRenderParameterMap().size());
}
@Test
public void testClearAllRenderParametersDoesNotPropagateExceptionIfRedirectAlreadySentAtTimeOfCall() throws Exception {
MockActionResponse response = new MockActionResponse() {
@SuppressWarnings("unchecked")
public void setRenderParameters(Map parameters) {
throw new IllegalStateException();
}
};
response.setRenderParameter("William", "Baskerville");
response.setRenderParameter("Adso", "Melk");
PortletUtils.clearAllRenderParameters(response);
assertEquals("The render parameters map must not be cleared if ActionResponse.sendRedirect() has been called (already).",
2, response.getRenderParameterMap().size());
}
@Test
public void testHasSubmitParameterWithStraightNameMatch() throws Exception {
final String targetSubmitParameter = "William";
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetSubmitParameter, "Baskerville");
request.setParameter("Adso", "Melk");
request.setParameter("dominican_Bernard", "Gui");
assertTrue(PortletUtils.hasSubmitParameter(request, targetSubmitParameter));
}
@Test
public void testHasSubmitParameterWithPrefixedParameterMatch() throws Exception {
final String bareParameterName = "William";
final String targetParameterName = bareParameterName + WebUtils.SUBMIT_IMAGE_SUFFIXES[0];
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetParameterName, "Baskerville");
request.setParameter("Adso", "Melk");
assertTrue(PortletUtils.hasSubmitParameter(request, bareParameterName));
}
@Test
public void testHasSubmitParameterWithNoParameterMatch() throws Exception {
MockPortletRequest request = new MockPortletRequest();
request.setParameter("Bill", "Baskerville");
request.setParameter("Adso", "Melk");
assertFalse(PortletUtils.hasSubmitParameter(request, "William"));
}
@Test(expected=IllegalArgumentException.class)
public void testHasSubmitParameterWithNullRequest() throws Exception {
PortletUtils.hasSubmitParameter(null, "bingo");
}
@SuppressWarnings("unchecked")
@Test(expected=IllegalArgumentException.class)
public void testExposeRequestAttributesWithNullRequest() throws Exception {
PortletUtils.exposeRequestAttributes(null, Collections.EMPTY_MAP);
}
@Test(expected=IllegalArgumentException.class)
public void testExposeRequestAttributesWithNullAttributesMap() throws Exception {
PortletUtils.exposeRequestAttributes(new MockPortletRequest(), null);
}
@SuppressWarnings("unchecked")
@Test
public void testExposeRequestAttributesSunnyDay() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map<String, String> attributes = new HashMap<String, String>();
attributes.put("ace", "Rick Hunter");
attributes.put("mentor", "Roy Fokker");
PortletUtils.exposeRequestAttributes(request, attributes);
assertEquals("Rick Hunter", request.getAttribute("ace"));
assertEquals("Roy Fokker", request.getAttribute("mentor"));
}
@SuppressWarnings("unchecked")
@Test
public void testExposeRequestAttributesWithEmptyAttributesMapIsAnIdempotentOperation() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map<String, String> attributes = new HashMap<String, String>();
PortletUtils.exposeRequestAttributes(request, attributes);
}
@Test(expected=IllegalArgumentException.class)
public void testGetOrCreateSessionAttributeWithNullSession() throws Exception {
PortletUtils.getOrCreateSessionAttribute(null, "bean", TestBean.class);
}
@Test
public void testGetOrCreateSessionAttributeJustReturnsAttributeIfItAlreadyExists() throws Exception {
MockPortletSession session = new MockPortletSession();
final TestBean expectedAttribute = new TestBean("Donna Tartt");
session.setAttribute("donna", expectedAttribute);
Object actualAttribute = PortletUtils.getOrCreateSessionAttribute(session, "donna", TestBean.class);
assertSame(expectedAttribute, actualAttribute);
}
@Test
public void testGetOrCreateSessionAttributeCreatesAttributeIfItDoesNotAlreadyExist() throws Exception {
MockPortletSession session = new MockPortletSession();
Object actualAttribute = PortletUtils.getOrCreateSessionAttribute(session, "bean", TestBean.class);
assertNotNull(actualAttribute);
assertEquals("Wrong type of object being instantiated", TestBean.class, actualAttribute.getClass());
}
@Test(expected=IllegalArgumentException.class)
public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndNullClass() throws Exception {
PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", null);
}
@Test(expected=IllegalArgumentException.class)
public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndClassThatIsAnInterfaceType() throws Exception {
PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", ITestBean.class);
}
@Test(expected=IllegalArgumentException.class)
public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndClassWithNoPublicCtor() throws Exception {
PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", NoPublicCtor.class);
}
@Test(expected=IllegalArgumentException.class)
public void testGetSessionMutexWithNullSession() throws Exception {
PortletUtils.getSessionMutex(null);
}
@Test
public void testGetSessionMutexWithNoExistingSessionMutexDefinedJustReturnsTheSessionArgument() throws Exception {
MockPortletSession session = new MockPortletSession();
Object sessionMutex = PortletUtils.getSessionMutex(session);
assertNotNull("PortletUtils.getSessionMutex(..) must never return a null mutex", sessionMutex);
assertSame("PortletUtils.getSessionMutex(..) must return the exact same PortletSession supplied as an argument if no mutex has been bound as a Session attribute beforehand",
session, sessionMutex);
}
@Test
public void testGetSessionMutexWithExistingSessionMutexReturnsTheExistingSessionMutex() throws Exception {
MockPortletSession session = new MockPortletSession();
Object expectSessionMutex = new Object();
session.setAttribute(WebUtils.SESSION_MUTEX_ATTRIBUTE, expectSessionMutex, PortletSession.APPLICATION_SCOPE);
Object actualSessionMutex = PortletUtils.getSessionMutex(session);
assertNotNull("PortletUtils.getSessionMutex(..) must never return a null mutex", actualSessionMutex);
assertSame("PortletUtils.getSessionMutex(..) must return the bound mutex attribute if a mutex has been bound as a Session attribute beforehand",
expectSessionMutex, actualSessionMutex);
}
@Test(expected=IllegalArgumentException.class)
public void testGetSessionAttributeWithNullPortletRequest() throws Exception {
PortletUtils.getSessionAttribute(null, "foo");
}
@Test(expected=IllegalArgumentException.class)
public void testGetRequiredSessionAttributeWithNullPortletRequest() throws Exception {
PortletUtils.getRequiredSessionAttribute(null, "foo");
}
@Test(expected=IllegalArgumentException.class)
public void testSetSessionAttributeWithNullPortletRequest() throws Exception {
PortletUtils.setSessionAttribute(null, "foo", "bar");
}
@Test
public void testGetSessionAttributeDoes_Not_CreateANewSession() throws Exception {
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(null);
replay(request);
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNull("Must return null if session attribute does not exist (or if Session does not exist)", sessionAttribute);
verify(request);
}
@Test
public void testGetSessionAttributeWithExistingSession() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute("foo", "foo");
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(session);
replay(request);
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
verify(request);
}
@Test
public void testGetRequiredSessionAttributeWithExistingSession() throws Exception {
MockPortletSession session = new MockPortletSession();
session.setAttribute("foo", "foo");
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(session);
replay(request);
Object sessionAttribute = PortletUtils.getRequiredSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
verify(request);
}
@Test
public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception {
MockPortletSession session = new MockPortletSession();
final PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(session);
replay(request);
try {
PortletUtils.getRequiredSessionAttribute(request, "foo");
fail("expected IllegalStateException");
} catch (IllegalStateException ex) { /* expected */ }
verify(request);
}
@Test
public void testSetSessionAttributeWithExistingSessionAndNullValue() throws Exception {
PortletSession session = createMock(PortletSession.class);
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(session); // must not create Session for null value...
session.removeAttribute("foo", PortletSession.APPLICATION_SCOPE);
replay(request, session);
PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE);
verify(request, session);
}
@Test
public void testSetSessionAttributeWithNoExistingSessionAndNullValue() throws Exception {
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(null); // must not create Session for null value...
replay(request);
PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE);
verify(request);
}
@Test
public void testSetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
PortletSession session = createMock(PortletSession.class);
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession()).andReturn(session); // must not create Session ...
session.setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE);
replay(request, session);
PortletUtils.setSessionAttribute(request, "foo", "foo", PortletSession.APPLICATION_SCOPE);
verify(request, session);
}
@Test
public void testGetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
PortletSession session = createMock(PortletSession.class);
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(session);
expect(session.getAttribute("foo", PortletSession.APPLICATION_SCOPE)).andReturn("foo");
replay(request, session);
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo", PortletSession.APPLICATION_SCOPE);
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
verify(request, session);
}
@Test
public void testGetSessionAttributeWithExistingSessionDefaultsToPortletScope() throws Exception {
PortletSession session = createMock(PortletSession.class);
PortletRequest request = createMock(PortletRequest.class);
expect(request.getPortletSession(false)).andReturn(session);
expect(session.getAttribute("foo", PortletSession.PORTLET_SCOPE)).andReturn("foo");
replay(request, session);
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
verify(request, session);
}
private static final class NoPublicCtor {
private NoPublicCtor() {
throw new IllegalArgumentException("Just for eclipse...");
}
}
}

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<!-- Appenders -->
<appender name="console" class="org.apache.log4j.ConsoleAppender">
<param name="Target" value="System.out" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%-5p: %c - %m%n" />
</layout>
</appender>
<logger name="org.springframework.beans">
<level value="warn" />
</logger>
<logger name="org.springframework.binding">
<level value="debug" />
</logger>
<!-- Root Logger -->
<root>
<priority value="warn" />
<appender-ref ref="console" />
</root>
</log4j:configuration>