moving unit tests from .testsuite -> .core, .beans, .web, .web.portlet, .web.servlet
This commit is contained in:
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 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.mock.web;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
|
||||
import javax.servlet.ServletInputStream;
|
||||
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* Delegating implementation of {@link javax.servlet.ServletInputStream}.
|
||||
*
|
||||
* <p>Used by {@link org.springframework.mock.web.MockHttpServletRequest}; typically not directly
|
||||
* used for testing application controllers.
|
||||
*
|
||||
* @author Juergen Hoeller
|
||||
* @since 1.0.2
|
||||
* @see org.springframework.mock.web.MockHttpServletRequest
|
||||
*/
|
||||
public class DelegatingServletInputStream extends ServletInputStream {
|
||||
|
||||
private final InputStream sourceStream;
|
||||
|
||||
|
||||
/**
|
||||
* Create a DelegatingServletInputStream for the given source stream.
|
||||
* @param sourceStream the source stream (never <code>null</code>)
|
||||
*/
|
||||
public DelegatingServletInputStream(InputStream sourceStream) {
|
||||
Assert.notNull(sourceStream, "Source InputStream must not be null");
|
||||
this.sourceStream = sourceStream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the underlying source stream (never <code>null</code>).
|
||||
*/
|
||||
public final InputStream getSourceStream() {
|
||||
return this.sourceStream;
|
||||
}
|
||||
|
||||
|
||||
public int read() throws IOException {
|
||||
return this.sourceStream.read();
|
||||
}
|
||||
|
||||
public void close() throws IOException {
|
||||
super.close();
|
||||
this.sourceStream.close();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import org.springframework.core.enums.ShortCodedLabeledEnum;
|
||||
|
||||
/**
|
||||
* @author Rob Harrop
|
||||
*/
|
||||
public class Colour extends ShortCodedLabeledEnum {
|
||||
|
||||
public static final Colour RED = new Colour(0, "RED");
|
||||
public static final Colour BLUE = new Colour(1, "BLUE");
|
||||
public static final Colour GREEN = new Colour(2, "GREEN");
|
||||
public static final Colour PURPLE = new Colour(3, "PURPLE");
|
||||
|
||||
private Colour(int code, String label) {
|
||||
super(code, label);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.io.Serializable;
|
||||
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 21.08.2003
|
||||
*/
|
||||
public class DerivedTestBean extends TestBean implements Serializable, BeanNameAware, DisposableBean {
|
||||
|
||||
private String beanName;
|
||||
|
||||
private boolean initialized;
|
||||
|
||||
private boolean destroyed;
|
||||
|
||||
|
||||
public DerivedTestBean() {
|
||||
}
|
||||
|
||||
public DerivedTestBean(String[] names) {
|
||||
if (names == null || names.length < 2) {
|
||||
throw new IllegalArgumentException("Invalid names array");
|
||||
}
|
||||
setName(names[0]);
|
||||
setBeanName(names[1]);
|
||||
}
|
||||
|
||||
public static DerivedTestBean create(String[] names) {
|
||||
return new DerivedTestBean(names);
|
||||
}
|
||||
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
if (this.beanName == null || beanName == null) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setSpouseRef(String name) {
|
||||
setSpouse(new TestBean(name));
|
||||
}
|
||||
|
||||
|
||||
public void initialize() {
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
public boolean wasInitialized() {
|
||||
return initialized;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean wasDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
public interface INestedTestBean {
|
||||
|
||||
public String getCompany();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
public interface IOther {
|
||||
|
||||
void absquatulate();
|
||||
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Interface used for {@link org.springframework.beans.TestBean}.
|
||||
*
|
||||
* <p>Two methods are the same as on Person, but if this
|
||||
* extends person it breaks quite a few tests..
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public interface ITestBean {
|
||||
|
||||
int getAge();
|
||||
|
||||
void setAge(int age);
|
||||
|
||||
String getName();
|
||||
|
||||
void setName(String name);
|
||||
|
||||
ITestBean getSpouse();
|
||||
|
||||
void setSpouse(ITestBean spouse);
|
||||
|
||||
ITestBean[] getSpouses();
|
||||
|
||||
String[] getStringArray();
|
||||
|
||||
void setStringArray(String[] stringArray);
|
||||
|
||||
/**
|
||||
* Throws a given (non-null) exception.
|
||||
*/
|
||||
void exceptional(Throwable t) throws Throwable;
|
||||
|
||||
Object returnsThis();
|
||||
|
||||
INestedTestBean getDoctor();
|
||||
|
||||
INestedTestBean getLawyer();
|
||||
|
||||
IndexedTestBean getNestedIndexedBean();
|
||||
|
||||
/**
|
||||
* Increment the age by one.
|
||||
* @return the previous age
|
||||
*/
|
||||
int haveBirthday();
|
||||
|
||||
void unreliableFileOperation() throws IOException;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/*
|
||||
* Copyright 2002-2006 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.SortedMap;
|
||||
import java.util.SortedSet;
|
||||
import java.util.TreeSet;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 11.11.2003
|
||||
*/
|
||||
public class IndexedTestBean {
|
||||
|
||||
private TestBean[] array;
|
||||
|
||||
private Collection collection;
|
||||
|
||||
private List list;
|
||||
|
||||
private Set set;
|
||||
|
||||
private SortedSet sortedSet;
|
||||
|
||||
private Map map;
|
||||
|
||||
private SortedMap sortedMap;
|
||||
|
||||
|
||||
public IndexedTestBean() {
|
||||
this(true);
|
||||
}
|
||||
|
||||
public IndexedTestBean(boolean populate) {
|
||||
if (populate) {
|
||||
populate();
|
||||
}
|
||||
}
|
||||
|
||||
public void populate() {
|
||||
TestBean tb0 = new TestBean("name0", 0);
|
||||
TestBean tb1 = new TestBean("name1", 0);
|
||||
TestBean tb2 = new TestBean("name2", 0);
|
||||
TestBean tb3 = new TestBean("name3", 0);
|
||||
TestBean tb4 = new TestBean("name4", 0);
|
||||
TestBean tb5 = new TestBean("name5", 0);
|
||||
TestBean tb6 = new TestBean("name6", 0);
|
||||
TestBean tb7 = new TestBean("name7", 0);
|
||||
TestBean tbX = new TestBean("nameX", 0);
|
||||
TestBean tbY = new TestBean("nameY", 0);
|
||||
this.array = new TestBean[] {tb0, tb1};
|
||||
this.list = new ArrayList();
|
||||
this.list.add(tb2);
|
||||
this.list.add(tb3);
|
||||
this.set = new TreeSet();
|
||||
this.set.add(tb6);
|
||||
this.set.add(tb7);
|
||||
this.map = new HashMap();
|
||||
this.map.put("key1", tb4);
|
||||
this.map.put("key2", tb5);
|
||||
this.map.put("key.3", tb5);
|
||||
List list = new ArrayList();
|
||||
list.add(tbX);
|
||||
list.add(tbY);
|
||||
this.map.put("key4", list);
|
||||
}
|
||||
|
||||
|
||||
public TestBean[] getArray() {
|
||||
return array;
|
||||
}
|
||||
|
||||
public void setArray(TestBean[] array) {
|
||||
this.array = array;
|
||||
}
|
||||
|
||||
public Collection getCollection() {
|
||||
return collection;
|
||||
}
|
||||
|
||||
public void setCollection(Collection collection) {
|
||||
this.collection = collection;
|
||||
}
|
||||
|
||||
public List getList() {
|
||||
return list;
|
||||
}
|
||||
|
||||
public void setList(List list) {
|
||||
this.list = list;
|
||||
}
|
||||
|
||||
public Set getSet() {
|
||||
return set;
|
||||
}
|
||||
|
||||
public void setSet(Set set) {
|
||||
this.set = set;
|
||||
}
|
||||
|
||||
public SortedSet getSortedSet() {
|
||||
return sortedSet;
|
||||
}
|
||||
|
||||
public void setSortedSet(SortedSet sortedSet) {
|
||||
this.sortedSet = sortedSet;
|
||||
}
|
||||
|
||||
public Map getMap() {
|
||||
return map;
|
||||
}
|
||||
|
||||
public void setMap(Map map) {
|
||||
this.map = map;
|
||||
}
|
||||
|
||||
public SortedMap getSortedMap() {
|
||||
return sortedMap;
|
||||
}
|
||||
|
||||
public void setSortedMap(SortedMap sortedMap) {
|
||||
this.sortedMap = sortedMap;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
/**
|
||||
* Simple nested test bean used for testing bean factories, AOP framework etc.
|
||||
*
|
||||
* @author Trevor D. Cook
|
||||
* @since 30.09.2003
|
||||
*/
|
||||
public class NestedTestBean implements INestedTestBean {
|
||||
|
||||
private String company = "";
|
||||
|
||||
public NestedTestBean() {
|
||||
}
|
||||
|
||||
public NestedTestBean(String company) {
|
||||
setCompany(company);
|
||||
}
|
||||
|
||||
public void setCompany(String company) {
|
||||
this.company = (company != null ? company : "");
|
||||
}
|
||||
|
||||
public String getCompany() {
|
||||
return company;
|
||||
}
|
||||
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof NestedTestBean)) {
|
||||
return false;
|
||||
}
|
||||
NestedTestBean ntb = (NestedTestBean) obj;
|
||||
return this.company.equals(ntb.company);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.company.hashCode();
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "NestedTestBean: " + this.company;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
* Copyright 2002-2008 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.BeanFactoryAware;
|
||||
import org.springframework.beans.factory.BeanNameAware;
|
||||
import org.springframework.util.ObjectUtils;
|
||||
|
||||
/**
|
||||
* Simple test bean used for testing bean factories, the AOP framework etc.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Juergen Hoeller
|
||||
* @since 15 April 2001
|
||||
*/
|
||||
public class TestBean implements BeanNameAware, BeanFactoryAware, ITestBean, IOther, Comparable {
|
||||
|
||||
private String beanName;
|
||||
|
||||
private String country;
|
||||
|
||||
private BeanFactory beanFactory;
|
||||
|
||||
private boolean postProcessed;
|
||||
|
||||
private String name;
|
||||
|
||||
private String sex;
|
||||
|
||||
private int age;
|
||||
|
||||
private boolean jedi;
|
||||
|
||||
private ITestBean[] spouses;
|
||||
|
||||
private String touchy;
|
||||
|
||||
private String[] stringArray;
|
||||
|
||||
private Integer[] someIntegerArray;
|
||||
|
||||
private Date date = new Date();
|
||||
|
||||
private Float myFloat = new Float(0.0);
|
||||
|
||||
private Collection friends = new LinkedList();
|
||||
|
||||
private Set someSet = new HashSet();
|
||||
|
||||
private Map someMap = new HashMap();
|
||||
|
||||
private List someList = new ArrayList();
|
||||
|
||||
private Properties someProperties = new Properties();
|
||||
|
||||
private INestedTestBean doctor = new NestedTestBean();
|
||||
|
||||
private INestedTestBean lawyer = new NestedTestBean();
|
||||
|
||||
private IndexedTestBean nestedIndexedBean;
|
||||
|
||||
private boolean destroyed;
|
||||
|
||||
private Number someNumber;
|
||||
|
||||
private Colour favouriteColour;
|
||||
|
||||
private Boolean someBoolean;
|
||||
|
||||
private List otherColours;
|
||||
|
||||
private List pets;
|
||||
|
||||
|
||||
public TestBean() {
|
||||
}
|
||||
|
||||
public TestBean(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public TestBean(String name, int age) {
|
||||
this.name = name;
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public TestBean(ITestBean spouse, Properties someProperties) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public TestBean(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public TestBean(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public TestBean(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public TestBean(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.beanFactory = beanFactory;
|
||||
}
|
||||
|
||||
public BeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
public void setPostProcessed(boolean postProcessed) {
|
||||
this.postProcessed = postProcessed;
|
||||
}
|
||||
|
||||
public boolean isPostProcessed() {
|
||||
return postProcessed;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getSex() {
|
||||
return sex;
|
||||
}
|
||||
|
||||
public void setSex(String sex) {
|
||||
this.sex = sex;
|
||||
if (this.name == null) {
|
||||
this.name = sex;
|
||||
}
|
||||
}
|
||||
|
||||
public int getAge() {
|
||||
return age;
|
||||
}
|
||||
|
||||
public void setAge(int age) {
|
||||
this.age = age;
|
||||
}
|
||||
|
||||
public boolean isJedi() {
|
||||
return jedi;
|
||||
}
|
||||
|
||||
public void setJedi(boolean jedi) {
|
||||
this.jedi = jedi;
|
||||
}
|
||||
|
||||
public ITestBean getSpouse() {
|
||||
return (spouses != null ? spouses[0] : null);
|
||||
}
|
||||
|
||||
public void setSpouse(ITestBean spouse) {
|
||||
this.spouses = new ITestBean[] {spouse};
|
||||
}
|
||||
|
||||
public ITestBean[] getSpouses() {
|
||||
return spouses;
|
||||
}
|
||||
|
||||
public String getTouchy() {
|
||||
return touchy;
|
||||
}
|
||||
|
||||
public void setTouchy(String touchy) throws Exception {
|
||||
if (touchy.indexOf('.') != -1) {
|
||||
throw new Exception("Can't contain a .");
|
||||
}
|
||||
if (touchy.indexOf(',') != -1) {
|
||||
throw new NumberFormatException("Number format exception: contains a ,");
|
||||
}
|
||||
this.touchy = touchy;
|
||||
}
|
||||
|
||||
public String getCountry() {
|
||||
return country;
|
||||
}
|
||||
|
||||
public void setCountry(String country) {
|
||||
this.country = country;
|
||||
}
|
||||
|
||||
public String[] getStringArray() {
|
||||
return stringArray;
|
||||
}
|
||||
|
||||
public void setStringArray(String[] stringArray) {
|
||||
this.stringArray = stringArray;
|
||||
}
|
||||
|
||||
public Integer[] getSomeIntegerArray() {
|
||||
return someIntegerArray;
|
||||
}
|
||||
|
||||
public void setSomeIntegerArray(Integer[] someIntegerArray) {
|
||||
this.someIntegerArray = someIntegerArray;
|
||||
}
|
||||
|
||||
public Date getDate() {
|
||||
return date;
|
||||
}
|
||||
|
||||
public void setDate(Date date) {
|
||||
this.date = date;
|
||||
}
|
||||
|
||||
public Float getMyFloat() {
|
||||
return myFloat;
|
||||
}
|
||||
|
||||
public void setMyFloat(Float myFloat) {
|
||||
this.myFloat = myFloat;
|
||||
}
|
||||
|
||||
public Collection getFriends() {
|
||||
return friends;
|
||||
}
|
||||
|
||||
public void setFriends(Collection friends) {
|
||||
this.friends = friends;
|
||||
}
|
||||
|
||||
public Set getSomeSet() {
|
||||
return someSet;
|
||||
}
|
||||
|
||||
public void setSomeSet(Set someSet) {
|
||||
this.someSet = someSet;
|
||||
}
|
||||
|
||||
public Map getSomeMap() {
|
||||
return someMap;
|
||||
}
|
||||
|
||||
public void setSomeMap(Map someMap) {
|
||||
this.someMap = someMap;
|
||||
}
|
||||
|
||||
public List getSomeList() {
|
||||
return someList;
|
||||
}
|
||||
|
||||
public void setSomeList(List someList) {
|
||||
this.someList = someList;
|
||||
}
|
||||
|
||||
public Properties getSomeProperties() {
|
||||
return someProperties;
|
||||
}
|
||||
|
||||
public void setSomeProperties(Properties someProperties) {
|
||||
this.someProperties = someProperties;
|
||||
}
|
||||
|
||||
public INestedTestBean getDoctor() {
|
||||
return doctor;
|
||||
}
|
||||
|
||||
public void setDoctor(INestedTestBean doctor) {
|
||||
this.doctor = doctor;
|
||||
}
|
||||
|
||||
public INestedTestBean getLawyer() {
|
||||
return lawyer;
|
||||
}
|
||||
|
||||
public void setLawyer(INestedTestBean lawyer) {
|
||||
this.lawyer = lawyer;
|
||||
}
|
||||
|
||||
public Number getSomeNumber() {
|
||||
return someNumber;
|
||||
}
|
||||
|
||||
public void setSomeNumber(Number someNumber) {
|
||||
this.someNumber = someNumber;
|
||||
}
|
||||
|
||||
public Colour getFavouriteColour() {
|
||||
return favouriteColour;
|
||||
}
|
||||
|
||||
public void setFavouriteColour(Colour favouriteColour) {
|
||||
this.favouriteColour = favouriteColour;
|
||||
}
|
||||
|
||||
public Boolean getSomeBoolean() {
|
||||
return someBoolean;
|
||||
}
|
||||
|
||||
public void setSomeBoolean(Boolean someBoolean) {
|
||||
this.someBoolean = someBoolean;
|
||||
}
|
||||
|
||||
public IndexedTestBean getNestedIndexedBean() {
|
||||
return nestedIndexedBean;
|
||||
}
|
||||
|
||||
public void setNestedIndexedBean(IndexedTestBean nestedIndexedBean) {
|
||||
this.nestedIndexedBean = nestedIndexedBean;
|
||||
}
|
||||
|
||||
public List getOtherColours() {
|
||||
return otherColours;
|
||||
}
|
||||
|
||||
public void setOtherColours(List otherColours) {
|
||||
this.otherColours = otherColours;
|
||||
}
|
||||
|
||||
public List getPets() {
|
||||
return pets;
|
||||
}
|
||||
|
||||
public void setPets(List pets) {
|
||||
this.pets = pets;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#exceptional(Throwable)
|
||||
*/
|
||||
public void exceptional(Throwable t) throws Throwable {
|
||||
if (t != null) {
|
||||
throw t;
|
||||
}
|
||||
}
|
||||
|
||||
public void unreliableFileOperation() throws IOException {
|
||||
throw new IOException();
|
||||
}
|
||||
/**
|
||||
* @see org.springframework.beans.ITestBean#returnsThis()
|
||||
*/
|
||||
public Object returnsThis() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @see org.springframework.beans.IOther#absquatulate()
|
||||
*/
|
||||
public void absquatulate() {
|
||||
}
|
||||
|
||||
public int haveBirthday() {
|
||||
return age++;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean wasDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
|
||||
public boolean equals(Object other) {
|
||||
if (this == other) {
|
||||
return true;
|
||||
}
|
||||
if (other == null || !(other instanceof TestBean)) {
|
||||
return false;
|
||||
}
|
||||
TestBean tb2 = (TestBean) other;
|
||||
return (ObjectUtils.nullSafeEquals(this.name, tb2.name) && this.age == tb2.age);
|
||||
}
|
||||
|
||||
public int hashCode() {
|
||||
return this.age;
|
||||
}
|
||||
|
||||
public int compareTo(Object other) {
|
||||
if (this.name != null && other instanceof TestBean) {
|
||||
return this.name.compareTo(((TestBean) other).getName());
|
||||
}
|
||||
else {
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return this.name;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,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(null);
|
||||
fail("Can't get null bean");
|
||||
}
|
||||
catch (IllegalArgumentException ex) {
|
||||
// OK
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that InitializingBean objects receive the afterPropertiesSet() callback
|
||||
*/
|
||||
public void testInitializingBeanCallback() {
|
||||
MustBeInitialized mbi = (MustBeInitialized) getBeanFactory().getBean("mustBeInitialized");
|
||||
// The dummy business method will throw an exception if the
|
||||
// afterPropertiesSet() callback wasn't invoked
|
||||
mbi.businessMethod();
|
||||
}
|
||||
|
||||
/**
|
||||
* Test that InitializingBean/BeanFactoryAware/DisposableBean objects receive the
|
||||
* afterPropertiesSet() callback before BeanFactoryAware callbacks
|
||||
*/
|
||||
public void testLifecycleCallbacks() {
|
||||
LifecycleBean lb = (LifecycleBean) getBeanFactory().getBean("lifecycle");
|
||||
Assert.assertEquals("lifecycle", lb.getBeanName());
|
||||
// The dummy business method will throw an exception if the
|
||||
// necessary callbacks weren't invoked in the right order.
|
||||
lb.businessMethod();
|
||||
assertTrue("Not destroyed", !lb.isDestroyed());
|
||||
}
|
||||
|
||||
public void testFindsValidInstance() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod");
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
TestBean rod = (TestBean) o;
|
||||
assertTrue("rod.name is Rod", rod.getName().equals("Rod"));
|
||||
assertTrue("rod.age is 31", rod.getAge() == 31);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetInstanceByMatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", TestBean.class);
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance with matching class");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetInstanceByNonmatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
|
||||
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
|
||||
}
|
||||
catch (BeanNotOfRequiredTypeException ex) {
|
||||
// So far, so good
|
||||
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
|
||||
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
|
||||
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
|
||||
assertTrue("Actual type is correct", ex.getActualType() == getBeanFactory().getBean("rod").getClass());
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetSharedInstanceByMatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", TestBean.class);
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance with matching class");
|
||||
}
|
||||
}
|
||||
|
||||
public void testGetSharedInstanceByMatchingClassNoCatch() {
|
||||
Object o = getBeanFactory().getBean("rod", TestBean.class);
|
||||
assertTrue("Rod bean is a TestBean", o instanceof TestBean);
|
||||
}
|
||||
|
||||
public void testGetSharedInstanceByNonmatchingClass() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod", BeanFactory.class);
|
||||
fail("Rod bean is not of type BeanFactory; getBeanInstance(rod, BeanFactory.class) should throw BeanNotOfRequiredTypeException");
|
||||
}
|
||||
catch (BeanNotOfRequiredTypeException ex) {
|
||||
// So far, so good
|
||||
assertTrue("Exception has correct bean name", ex.getBeanName().equals("rod"));
|
||||
assertTrue("Exception requiredType must be BeanFactory.class", ex.getRequiredType().equals(BeanFactory.class));
|
||||
assertTrue("Exception actualType as TestBean.class", TestBean.class.isAssignableFrom(ex.getActualType()));
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testSharedInstancesAreEqual() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("rod");
|
||||
assertTrue("Rod bean1 is a TestBean", o instanceof TestBean);
|
||||
Object o1 = getBeanFactory().getBean("rod");
|
||||
assertTrue("Rod bean2 is a TestBean", o1 instanceof TestBean);
|
||||
assertTrue("Object equals applies", o == o1);
|
||||
}
|
||||
catch (Exception ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testPrototypeInstancesAreIndependent() {
|
||||
TestBean tb1 = (TestBean) getBeanFactory().getBean("kathy");
|
||||
TestBean tb2 = (TestBean) getBeanFactory().getBean("kathy");
|
||||
assertTrue("ref equal DOES NOT apply", tb1 != tb2);
|
||||
assertTrue("object equal true", tb1.equals(tb2));
|
||||
tb1.setAge(1);
|
||||
tb2.setAge(2);
|
||||
assertTrue("1 age independent = 1", tb1.getAge() == 1);
|
||||
assertTrue("2 age independent = 2", tb2.getAge() == 2);
|
||||
assertTrue("object equal now false", !tb1.equals(tb2));
|
||||
}
|
||||
|
||||
public void testNotThere() {
|
||||
assertFalse(getBeanFactory().containsBean("Mr Squiggle"));
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("Mr Squiggle");
|
||||
fail("Can't find missing bean");
|
||||
}
|
||||
catch (BeansException ex) {
|
||||
//ex.printStackTrace();
|
||||
//fail("Shouldn't throw exception on getting valid instance");
|
||||
}
|
||||
}
|
||||
|
||||
public void testValidEmpty() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("validEmpty");
|
||||
assertTrue("validEmpty bean is a TestBean", o instanceof TestBean);
|
||||
TestBean ve = (TestBean) o;
|
||||
assertTrue("Valid empty has defaults", ve.getName() == null && ve.getAge() == 0 && ve.getSpouse() == null);
|
||||
}
|
||||
catch (BeansException ex) {
|
||||
ex.printStackTrace();
|
||||
fail("Shouldn't throw exception on valid empty");
|
||||
}
|
||||
}
|
||||
|
||||
public void xtestTypeMismatch() {
|
||||
try {
|
||||
Object o = getBeanFactory().getBean("typeMismatch");
|
||||
fail("Shouldn't succeed with type mismatch");
|
||||
}
|
||||
catch (BeanCreationException wex) {
|
||||
assertEquals("typeMismatch", wex.getBeanName());
|
||||
assertTrue(wex.getCause() instanceof PropertyBatchUpdateException);
|
||||
PropertyBatchUpdateException ex = (PropertyBatchUpdateException) wex.getCause();
|
||||
// Further tests
|
||||
assertTrue("Has one error ", ex.getExceptionCount() == 1);
|
||||
assertTrue("Error is for field age", ex.getPropertyAccessException("age") != null);
|
||||
assertTrue("We have rejected age in exception", ex.getPropertyAccessException("age").getPropertyChangeEvent().getNewValue().equals("34x"));
|
||||
}
|
||||
}
|
||||
|
||||
public void testGrandparentDefinitionFoundInBeanFactory() throws Exception {
|
||||
TestBean dad = (TestBean) getBeanFactory().getBean("father");
|
||||
assertTrue("Dad has correct name", dad.getName().equals("Albert"));
|
||||
}
|
||||
|
||||
public void testFactorySingleton() throws Exception {
|
||||
assertTrue(getBeanFactory().isSingleton("&singletonFactory"));
|
||||
assertTrue(getBeanFactory().isSingleton("singletonFactory"));
|
||||
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
|
||||
assertTrue("Singleton from factory has correct name, not " + tb.getName(), tb.getName().equals(DummyFactory.SINGLETON_NAME));
|
||||
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
|
||||
TestBean tb2 = (TestBean) getBeanFactory().getBean("singletonFactory");
|
||||
assertTrue("Singleton references ==", tb == tb2);
|
||||
assertTrue("FactoryBean is BeanFactoryAware", factory.getBeanFactory() != null);
|
||||
}
|
||||
|
||||
public void testFactoryPrototype() throws Exception {
|
||||
assertTrue(getBeanFactory().isSingleton("&prototypeFactory"));
|
||||
assertFalse(getBeanFactory().isSingleton("prototypeFactory"));
|
||||
TestBean tb = (TestBean) getBeanFactory().getBean("prototypeFactory");
|
||||
assertTrue(!tb.getName().equals(DummyFactory.SINGLETON_NAME));
|
||||
TestBean tb2 = (TestBean) getBeanFactory().getBean("prototypeFactory");
|
||||
assertTrue("Prototype references !=", tb != tb2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that we can get the factory bean itself.
|
||||
* This is only possible if we're dealing with a factory
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testGetFactoryItself() throws Exception {
|
||||
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
|
||||
assertTrue(factory != null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check that afterPropertiesSet gets called on factory
|
||||
* @throws Exception
|
||||
*/
|
||||
public void testFactoryIsInitialized() throws Exception {
|
||||
TestBean tb = (TestBean) getBeanFactory().getBean("singletonFactory");
|
||||
DummyFactory factory = (DummyFactory) getBeanFactory().getBean("&singletonFactory");
|
||||
assertTrue("Factory was initialized because it implemented InitializingBean", factory.wasInitialized());
|
||||
}
|
||||
|
||||
/**
|
||||
* It should be illegal to dereference a normal bean
|
||||
* as a factory
|
||||
*/
|
||||
public void testRejectsFactoryGetOnNormalBean() {
|
||||
try {
|
||||
getBeanFactory().getBean("&rod");
|
||||
fail("Shouldn't permit factory get on normal bean");
|
||||
}
|
||||
catch (BeanIsNotAFactoryException ex) {
|
||||
// Ok
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: refactor in AbstractBeanFactory (tests for AbstractBeanFactory)
|
||||
// and rename this class
|
||||
public void testAliasing() {
|
||||
BeanFactory bf = getBeanFactory();
|
||||
if (!(bf instanceof ConfigurableBeanFactory)) {
|
||||
return;
|
||||
}
|
||||
ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) bf;
|
||||
|
||||
String alias = "rods alias";
|
||||
try {
|
||||
cbf.getBean(alias);
|
||||
fail("Shouldn't permit factory get on normal bean");
|
||||
}
|
||||
catch (NoSuchBeanDefinitionException ex) {
|
||||
// Ok
|
||||
assertTrue(alias.equals(ex.getBeanName()));
|
||||
}
|
||||
|
||||
// Create alias
|
||||
cbf.registerAlias("rod", alias);
|
||||
Object rod = getBeanFactory().getBean("rod");
|
||||
Object aliasRod = getBeanFactory().getBean(alias);
|
||||
assertTrue(rod == aliasRod);
|
||||
}
|
||||
|
||||
|
||||
public static class TestBeanEditor extends PropertyEditorSupport {
|
||||
|
||||
public void setAsText(String text) {
|
||||
TestBean tb = new TestBean();
|
||||
StringTokenizer st = new StringTokenizer(text, "_");
|
||||
tb.setName(st.nextToken());
|
||||
tb.setAge(Integer.parseInt(st.nextToken()));
|
||||
setValue(tb);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,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"));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans.factory;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;
|
||||
|
||||
/**
|
||||
* Simple factory to allow testing of FactoryBean support in AbstractBeanFactory.
|
||||
* Depending on whether its singleton property is set, it will return a singleton
|
||||
* or a prototype instance.
|
||||
*
|
||||
* <p>Implements InitializingBean interface, so we can check that
|
||||
* factories get this lifecycle callback if they want.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since 10.03.2003
|
||||
*/
|
||||
public class DummyFactory
|
||||
implements FactoryBean, BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
|
||||
|
||||
public static final String SINGLETON_NAME = "Factory singleton";
|
||||
|
||||
private static boolean prototypeCreated;
|
||||
|
||||
/**
|
||||
* Clear static state.
|
||||
*/
|
||||
public static void reset() {
|
||||
prototypeCreated = false;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Default is for factories to return a singleton instance.
|
||||
*/
|
||||
private boolean singleton = true;
|
||||
|
||||
private String beanName;
|
||||
|
||||
private AutowireCapableBeanFactory beanFactory;
|
||||
|
||||
private boolean postProcessed;
|
||||
|
||||
private boolean initialized;
|
||||
|
||||
private TestBean testBean;
|
||||
|
||||
private TestBean otherTestBean;
|
||||
|
||||
|
||||
public DummyFactory() {
|
||||
this.testBean = new TestBean();
|
||||
this.testBean.setName(SINGLETON_NAME);
|
||||
this.testBean.setAge(25);
|
||||
}
|
||||
|
||||
/**
|
||||
* Return if the bean managed by this factory is a singleton.
|
||||
* @see FactoryBean#isSingleton()
|
||||
*/
|
||||
public boolean isSingleton() {
|
||||
return this.singleton;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set if the bean managed by this factory is a singleton.
|
||||
*/
|
||||
public void setSingleton(boolean singleton) {
|
||||
this.singleton = singleton;
|
||||
}
|
||||
|
||||
public void setBeanName(String beanName) {
|
||||
this.beanName = beanName;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.beanFactory = (AutowireCapableBeanFactory) beanFactory;
|
||||
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(this.testBean, this.beanName);
|
||||
}
|
||||
|
||||
public BeanFactory getBeanFactory() {
|
||||
return beanFactory;
|
||||
}
|
||||
|
||||
public void setPostProcessed(boolean postProcessed) {
|
||||
this.postProcessed = postProcessed;
|
||||
}
|
||||
|
||||
public boolean isPostProcessed() {
|
||||
return postProcessed;
|
||||
}
|
||||
|
||||
public void setOtherTestBean(TestBean otherTestBean) {
|
||||
this.otherTestBean = otherTestBean;
|
||||
this.testBean.setSpouse(otherTestBean);
|
||||
}
|
||||
|
||||
public TestBean getOtherTestBean() {
|
||||
return otherTestBean;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
if (initialized) {
|
||||
throw new RuntimeException("Cannot call afterPropertiesSet twice on the one bean");
|
||||
}
|
||||
this.initialized = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Was this initialized by invocation of the
|
||||
* afterPropertiesSet() method from the InitializingBean interface?
|
||||
*/
|
||||
public boolean wasInitialized() {
|
||||
return initialized;
|
||||
}
|
||||
|
||||
public static boolean wasPrototypeCreated() {
|
||||
return prototypeCreated;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Return the managed object, supporting both singleton
|
||||
* and prototype mode.
|
||||
* @see FactoryBean#getObject()
|
||||
*/
|
||||
public Object getObject() throws BeansException {
|
||||
if (isSingleton()) {
|
||||
return this.testBean;
|
||||
}
|
||||
else {
|
||||
TestBean prototype = new TestBean("prototype created at " + System.currentTimeMillis(), 11);
|
||||
if (this.beanFactory != null) {
|
||||
this.beanFactory.applyBeanPostProcessorsBeforeInitialization(prototype, this.beanName);
|
||||
}
|
||||
prototypeCreated = true;
|
||||
return prototype;
|
||||
}
|
||||
}
|
||||
|
||||
public Class getObjectType() {
|
||||
return TestBean.class;
|
||||
}
|
||||
|
||||
|
||||
public void destroy() {
|
||||
if (this.testBean != null) {
|
||||
this.testBean.setName(null);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans.factory;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
|
||||
/**
|
||||
* Simple test of BeanFactory initialization and lifecycle callbacks.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @author Colin Sampaleanu
|
||||
* @since 12.03.2003
|
||||
*/
|
||||
public class LifecycleBean implements BeanNameAware, BeanFactoryAware, InitializingBean, DisposableBean {
|
||||
|
||||
protected boolean initMethodDeclared = false;
|
||||
|
||||
protected String beanName;
|
||||
|
||||
protected BeanFactory owningFactory;
|
||||
|
||||
protected boolean postProcessedBeforeInit;
|
||||
|
||||
protected boolean inited;
|
||||
|
||||
protected boolean initedViaDeclaredInitMethod;
|
||||
|
||||
protected boolean postProcessedAfterInit;
|
||||
|
||||
protected boolean destroyed;
|
||||
|
||||
|
||||
public void setInitMethodDeclared(boolean initMethodDeclared) {
|
||||
this.initMethodDeclared = initMethodDeclared;
|
||||
}
|
||||
|
||||
public boolean isInitMethodDeclared() {
|
||||
return initMethodDeclared;
|
||||
}
|
||||
|
||||
public void setBeanName(String name) {
|
||||
this.beanName = name;
|
||||
}
|
||||
|
||||
public String getBeanName() {
|
||||
return beanName;
|
||||
}
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
this.owningFactory = beanFactory;
|
||||
}
|
||||
|
||||
public void postProcessBeforeInit() {
|
||||
if (this.inited || this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory called postProcessBeforeInit after afterPropertiesSet");
|
||||
}
|
||||
if (this.postProcessedBeforeInit) {
|
||||
throw new RuntimeException("Factory called postProcessBeforeInit twice");
|
||||
}
|
||||
this.postProcessedBeforeInit = true;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
if (this.owningFactory == null) {
|
||||
throw new RuntimeException("Factory didn't call setBeanFactory before afterPropertiesSet on lifecycle bean");
|
||||
}
|
||||
if (!this.postProcessedBeforeInit) {
|
||||
throw new RuntimeException("Factory didn't call postProcessBeforeInit before afterPropertiesSet on lifecycle bean");
|
||||
}
|
||||
if (this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory initialized via declared init method before initializing via afterPropertiesSet");
|
||||
}
|
||||
if (this.inited) {
|
||||
throw new RuntimeException("Factory called afterPropertiesSet twice");
|
||||
}
|
||||
this.inited = true;
|
||||
}
|
||||
|
||||
public void declaredInitMethod() {
|
||||
if (!this.inited) {
|
||||
throw new RuntimeException("Factory didn't call afterPropertiesSet before declared init method");
|
||||
}
|
||||
|
||||
if (this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory called declared init method twice");
|
||||
}
|
||||
this.initedViaDeclaredInitMethod = true;
|
||||
}
|
||||
|
||||
public void postProcessAfterInit() {
|
||||
if (!this.inited) {
|
||||
throw new RuntimeException("Factory called postProcessAfterInit before afterPropertiesSet");
|
||||
}
|
||||
if (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) {
|
||||
throw new RuntimeException("Factory called postProcessAfterInit before calling declared init method");
|
||||
}
|
||||
if (this.postProcessedAfterInit) {
|
||||
throw new RuntimeException("Factory called postProcessAfterInit twice");
|
||||
}
|
||||
this.postProcessedAfterInit = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dummy business method that will fail unless the factory
|
||||
* managed the bean's lifecycle correctly
|
||||
*/
|
||||
public void businessMethod() {
|
||||
if (!this.inited || (this.initMethodDeclared && !this.initedViaDeclaredInitMethod) ||
|
||||
!this.postProcessedAfterInit) {
|
||||
throw new RuntimeException("Factory didn't initialize lifecycle object correctly");
|
||||
}
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
if (this.destroyed) {
|
||||
throw new IllegalStateException("Already destroyed");
|
||||
}
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public boolean isDestroyed() {
|
||||
return destroyed;
|
||||
}
|
||||
|
||||
|
||||
public static class PostProcessor implements BeanPostProcessor {
|
||||
|
||||
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
|
||||
if (bean instanceof LifecycleBean) {
|
||||
((LifecycleBean) bean).postProcessBeforeInit();
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
|
||||
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
|
||||
if (bean instanceof LifecycleBean) {
|
||||
((LifecycleBean) bean).postProcessAfterInit();
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.beans.factory;
|
||||
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
|
||||
/**
|
||||
* Simple test of BeanFactory initialization
|
||||
* @author Rod Johnson
|
||||
* @since 12.03.2003
|
||||
*/
|
||||
public class MustBeInitialized implements InitializingBean {
|
||||
|
||||
private boolean inited;
|
||||
|
||||
/**
|
||||
* @see InitializingBean#afterPropertiesSet()
|
||||
*/
|
||||
public void afterPropertiesSet() throws Exception {
|
||||
this.inited = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dummy business method that will fail unless the factory
|
||||
* managed the bean's lifecycle correctly
|
||||
*/
|
||||
public void businessMethod() {
|
||||
if (!this.inited)
|
||||
throw new RuntimeException("Factory didn't call afterPropertiesSet() on MustBeInitialized object");
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.context;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
import org.springframework.context.ApplicationContextException;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
|
||||
public class ACATester implements ApplicationContextAware {
|
||||
|
||||
private ApplicationContext ac;
|
||||
|
||||
public void setApplicationContext(ApplicationContext ctx) throws ApplicationContextException {
|
||||
// check reinitialization
|
||||
if (this.ac != null) {
|
||||
throw new IllegalStateException("Already initialized");
|
||||
}
|
||||
|
||||
// check message source availability
|
||||
if (ctx != null) {
|
||||
try {
|
||||
ctx.getMessage("code1", null, Locale.getDefault());
|
||||
}
|
||||
catch (NoSuchMessageException ex) {
|
||||
// expected
|
||||
}
|
||||
}
|
||||
|
||||
this.ac = ctx;
|
||||
}
|
||||
|
||||
public ApplicationContext getApplicationContext() {
|
||||
return ac;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.context;
|
||||
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.ApplicationContextAware;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class BeanThatBroadcasts implements ApplicationContextAware {
|
||||
|
||||
public ApplicationContext applicationContext;
|
||||
|
||||
public int receivedCount;
|
||||
|
||||
|
||||
public void setApplicationContext(ApplicationContext applicationContext) {
|
||||
this.applicationContext = applicationContext;
|
||||
if (applicationContext.getDisplayName().indexOf("listener") != -1) {
|
||||
applicationContext.getBean("listener");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
* Copyright 2002-2007 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.context;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A stub {@link ApplicationListener}.
|
||||
*
|
||||
* @author Thomas Risberg
|
||||
* @author Juergen Hoeller
|
||||
*/
|
||||
public class BeanThatListens implements ApplicationListener {
|
||||
|
||||
private BeanThatBroadcasts beanThatBroadcasts;
|
||||
|
||||
private int eventCount;
|
||||
|
||||
|
||||
public BeanThatListens() {
|
||||
}
|
||||
|
||||
public BeanThatListens(BeanThatBroadcasts beanThatBroadcasts) {
|
||||
this.beanThatBroadcasts = beanThatBroadcasts;
|
||||
Map beans = beanThatBroadcasts.applicationContext.getBeansOfType(BeanThatListens.class);
|
||||
if (!beans.isEmpty()) {
|
||||
throw new IllegalStateException("Shouldn't have found any BeanThatListens instances");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void onApplicationEvent(ApplicationEvent event) {
|
||||
eventCount++;
|
||||
if (beanThatBroadcasts != null) {
|
||||
beanThatBroadcasts.receivedCount++;
|
||||
}
|
||||
}
|
||||
|
||||
public int getEventCount() {
|
||||
return eventCount;
|
||||
}
|
||||
|
||||
public void zero() {
|
||||
eventCount = 0;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package org.springframework.context;
|
||||
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.BeanFactory;
|
||||
import org.springframework.beans.factory.LifecycleBean;
|
||||
|
||||
/**
|
||||
* Simple bean to test ApplicationContext lifecycle methods for beans
|
||||
*
|
||||
* @author Colin Sampaleanu
|
||||
* @since 03.07.2004
|
||||
*/
|
||||
public class LifecycleContextBean extends LifecycleBean implements ApplicationContextAware {
|
||||
|
||||
protected ApplicationContext owningContext;
|
||||
|
||||
public void setBeanFactory(BeanFactory beanFactory) {
|
||||
super.setBeanFactory(beanFactory);
|
||||
if (this.owningContext != null)
|
||||
throw new RuntimeException("Factory called setBeanFactory after setApplicationContext");
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
super.afterPropertiesSet();
|
||||
if (this.owningContext == null)
|
||||
throw new RuntimeException("Factory didn't call setAppliationContext before afterPropertiesSet on lifecycle bean");
|
||||
}
|
||||
|
||||
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
|
||||
if (this.owningFactory == null)
|
||||
throw new RuntimeException("Factory called setApplicationContext before setBeanFactory");
|
||||
|
||||
this.owningContext = applicationContext;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package org.springframework.context;
|
||||
|
||||
import org.springframework.context.ApplicationEvent;
|
||||
import org.springframework.context.ApplicationListener;
|
||||
|
||||
/**
|
||||
* Listener that maintains a global count of events.
|
||||
*
|
||||
* @author Rod Johnson
|
||||
* @since January 21, 2001
|
||||
*/
|
||||
public class TestListener implements ApplicationListener {
|
||||
|
||||
private int eventCount;
|
||||
|
||||
public int getEventCount() {
|
||||
return eventCount;
|
||||
}
|
||||
|
||||
public void zeroCounter() {
|
||||
eventCount = 0;
|
||||
}
|
||||
|
||||
public void onApplicationEvent(ApplicationEvent e) {
|
||||
++eventCount;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,504 @@
|
||||
/*
|
||||
* 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 java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
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.Portlet;
|
||||
import javax.portlet.PortletConfig;
|
||||
import javax.portlet.PortletException;
|
||||
import javax.portlet.PortletRequest;
|
||||
import javax.portlet.RenderRequest;
|
||||
import javax.portlet.RenderResponse;
|
||||
|
||||
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.portlet.MockPortletConfig;
|
||||
import org.springframework.mock.web.portlet.MockPortletContext;
|
||||
import org.springframework.web.multipart.MaxUploadSizeExceededException;
|
||||
import org.springframework.web.multipart.MultipartException;
|
||||
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.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
|
||||
*/
|
||||
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.addPropertyValue("portletModeMap", portletModeMap);
|
||||
pvs.addPropertyValue("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.addPropertyValue("parameterMap", parameterMap);
|
||||
pvs.addPropertyValue("parameterName", "myParam");
|
||||
pvs.addPropertyValue("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.addPropertyValue("portletModeParameterMap", outerMap);
|
||||
pvs.addPropertyValue("order", "1");
|
||||
registerSingleton("handlerMapping1", PortletModeParameterHandlerMapping.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.addPropertyValue("order", "1");
|
||||
pvs.addPropertyValue("exceptionMappings",
|
||||
"java.lang.IllegalAccessException=failed-illegalaccess\n" +
|
||||
"PortletRequestBindingException=failed-binding\n" +
|
||||
"UnavailableException=failed-unavailable");
|
||||
pvs.addPropertyValue("defaultErrorView", "failed-default-1");
|
||||
registerSingleton("exceptionResolver", SimpleMappingExceptionResolver.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.addPropertyValue("order", "0");
|
||||
pvs.addPropertyValue("exceptionMappings",
|
||||
"java.lang.Exception=failed-exception\n" +
|
||||
"java.lang.RuntimeException=failed-runtime");
|
||||
List mappedHandlers = new ManagedList();
|
||||
mappedHandlers.add(new RuntimeBeanReference("exceptionThrowingHandler1"));
|
||||
pvs.addPropertyValue("mappedHandlers", mappedHandlers);
|
||||
pvs.addPropertyValue("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 static class MyHandlerInterceptor1 implements HandlerInterceptor {
|
||||
|
||||
public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void afterActionCompletion(ActionRequest request, ActionResponse response, Object handler, Exception ex) {
|
||||
}
|
||||
|
||||
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 implements HandlerInterceptor {
|
||||
|
||||
public boolean preHandleAction(ActionRequest request, ActionResponse response, Object handler) {
|
||||
return true;
|
||||
}
|
||||
|
||||
public void afterActionCompletion(ActionRequest request, ActionResponse response, Object handler, Exception ex) {
|
||||
}
|
||||
|
||||
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);
|
||||
Map files = new HashMap();
|
||||
files.put("someFile", "someFile");
|
||||
Map params = new HashMap();
|
||||
params.put("someParam", "someParam");
|
||||
return new DefaultMultipartActionRequest(request, files, params);
|
||||
}
|
||||
|
||||
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++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,989 @@
|
||||
/*
|
||||
* 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.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.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
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.request.ServletRequestAttributes;
|
||||
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.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(UnavailableException.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 (UnavailableException 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(UnavailableException.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(UnavailableException.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(UnavailableException.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(UnavailableException.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 {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest httpRequest = new MockHttpServletRequest(servletContext);
|
||||
httpRequest.addPreferredLocale(Locale.GERMAN);
|
||||
|
||||
// see RequestContextListener.requestInitialized()
|
||||
try {
|
||||
LocaleContextHolder.setLocale(httpRequest.getLocale());
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpRequest));
|
||||
|
||||
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
|
||||
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
|
||||
|
||||
MockActionRequest request = new MockActionRequest();
|
||||
MockActionResponse response = new MockActionResponse();
|
||||
request.setParameter("action", "form");
|
||||
request.setParameter("age", "29");
|
||||
simpleDispatcherPortlet.processAction(request, response);
|
||||
|
||||
assertSame(servletLocaleContext, LocaleContextHolder.getLocaleContext());
|
||||
assertSame(servletRequestAttrs, RequestContextHolder.getRequestAttributes());
|
||||
}
|
||||
finally {
|
||||
RequestContextHolder.resetRequestAttributes();
|
||||
LocaleContextHolder.resetLocaleContext();
|
||||
}
|
||||
}
|
||||
|
||||
public void testValidRenderRequestWithExistingThreadLocalRequestContext() throws IOException, PortletException {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest httpRequest = new MockHttpServletRequest(servletContext);
|
||||
httpRequest.addPreferredLocale(Locale.GERMAN);
|
||||
|
||||
// see RequestContextListener.requestInitialized()
|
||||
try {
|
||||
LocaleContextHolder.setLocale(httpRequest.getLocale());
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpRequest));
|
||||
|
||||
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
|
||||
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
|
||||
|
||||
MockRenderRequest request = new MockRenderRequest();
|
||||
MockRenderResponse response = new MockRenderResponse();
|
||||
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 {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest httpRequest = new MockHttpServletRequest(servletContext);
|
||||
httpRequest.addPreferredLocale(Locale.GERMAN);
|
||||
|
||||
// see RequestContextListener.requestInitialized()
|
||||
try {
|
||||
LocaleContextHolder.setLocale(httpRequest.getLocale());
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpRequest));
|
||||
|
||||
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
|
||||
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
|
||||
|
||||
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); // 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 {
|
||||
MockServletContext servletContext = new MockServletContext();
|
||||
MockHttpServletRequest httpRequest = new MockHttpServletRequest(servletContext);
|
||||
httpRequest.addPreferredLocale(Locale.GERMAN);
|
||||
|
||||
// see RequestContextListener.requestInitialized()
|
||||
try {
|
||||
LocaleContextHolder.setLocale(httpRequest.getLocale());
|
||||
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(httpRequest));
|
||||
|
||||
LocaleContext servletLocaleContext = LocaleContextHolder.getLocaleContext();
|
||||
RequestAttributes servletRequestAttrs = RequestContextHolder.getRequestAttributes();
|
||||
|
||||
MockRenderRequest request = new MockRenderRequest();
|
||||
MockRenderResponse response = new MockRenderResponse();
|
||||
try {
|
||||
simpleDispatcherPortlet.doDispatch(request, response);
|
||||
fail("should have failed to find a handler and raised an UnavailableException");
|
||||
}
|
||||
catch (UnavailableException 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();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.addPropertyValue("bindOnNewForm", "true");
|
||||
registerSingleton("controller2", TestFormController.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.addPropertyValue("requireSession", "true");
|
||||
pvs.addPropertyValue("sessionForm", "true");
|
||||
pvs.addPropertyValue("bindOnNewForm", "true");
|
||||
registerSingleton("controller3", TestFormController.class, pvs);
|
||||
|
||||
pvs = new MutablePropertyValues();
|
||||
pvs.addPropertyValue("requireSession", "true");
|
||||
pvs.addPropertyValue("sessionForm", "true");
|
||||
pvs.addPropertyValue("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));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* Copyright 2002-2005 the original author or authors.
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
package org.springframework.web.portlet.context;
|
||||
|
||||
import java.util.Locale;
|
||||
|
||||
import javax.servlet.ServletException;
|
||||
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.TestBean;
|
||||
import org.springframework.beans.factory.DisposableBean;
|
||||
import org.springframework.beans.factory.InitializingBean;
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.beans.factory.config.BeanPostProcessor;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.context.AbstractApplicationContextTests;
|
||||
import org.springframework.context.ConfigurableApplicationContext;
|
||||
import org.springframework.context.NoSuchMessageException;
|
||||
import org.springframework.context.TestListener;
|
||||
import org.springframework.mock.web.MockServletContext;
|
||||
import org.springframework.web.context.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;
|
||||
|
||||
protected ConfigurableApplicationContext createContext() throws Exception {
|
||||
InitAndIB.constructed = false;
|
||||
root = new XmlWebApplicationContext();
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
root.setServletContext(sc);
|
||||
root.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/applicationContext.xml"});
|
||||
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
|
||||
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
|
||||
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
|
||||
public Object postProcessBeforeInitialization(Object bean, String name) throws BeansException {
|
||||
if (bean instanceof TestBean) {
|
||||
((TestBean) bean).getFriends().add("myFriend");
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
public Object postProcessAfterInitialization(Object bean, String name) throws BeansException {
|
||||
return bean;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
root.refresh();
|
||||
XmlWebApplicationContext wac = new XmlWebApplicationContext();
|
||||
wac.setParent(root);
|
||||
wac.setServletContext(sc);
|
||||
wac.setNamespace("test-servlet");
|
||||
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
|
||||
wac.refresh();
|
||||
return wac;
|
||||
}
|
||||
|
||||
/**
|
||||
* Overridden as we can't trust superclass method
|
||||
* @see org.springframework.context.AbstractApplicationContextTests#testEvents()
|
||||
*/
|
||||
public void testEvents() throws Exception {
|
||||
TestListener listener = (TestListener) this.applicationContext.getBean("testListener");
|
||||
listener.zeroCounter();
|
||||
TestListener parentListener = (TestListener) this.applicationContext.getParent().getBean("parentListener");
|
||||
parentListener.zeroCounter();
|
||||
|
||||
parentListener.zeroCounter();
|
||||
assertTrue("0 events before publication", listener.getEventCount() == 0);
|
||||
assertTrue("0 parent events before publication", parentListener.getEventCount() == 0);
|
||||
this.applicationContext.publishEvent(new MyEvent(this));
|
||||
assertTrue("1 events after publication, not " + listener.getEventCount(), listener.getEventCount() == 1);
|
||||
assertTrue("1 parent events after publication", parentListener.getEventCount() == 1);
|
||||
}
|
||||
|
||||
public void testCount() {
|
||||
assertTrue("should have 14 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
|
||||
this.applicationContext.getBeanDefinitionCount() == 14);
|
||||
}
|
||||
|
||||
public void testWithoutMessageSource() throws Exception {
|
||||
MockServletContext sc = new MockServletContext("");
|
||||
XmlWebApplicationContext wac = new XmlWebApplicationContext();
|
||||
wac.setParent(root);
|
||||
wac.setServletContext(sc);
|
||||
wac.setNamespace("testNamespace");
|
||||
wac.setConfigLocations(new String[] {"/org/springframework/web/context/WEB-INF/test-servlet.xml"});
|
||||
wac.refresh();
|
||||
try {
|
||||
wac.getMessage("someMessage", null, Locale.getDefault());
|
||||
fail("Should have thrown NoSuchMessageException");
|
||||
}
|
||||
catch (NoSuchMessageException ex) {
|
||||
// expected;
|
||||
}
|
||||
String msg = wac.getMessage("someMessage", null, "default", Locale.getDefault());
|
||||
assertTrue("Default message returned", "default".equals(msg));
|
||||
}
|
||||
|
||||
public void testContextNesting() {
|
||||
TestBean father = (TestBean) this.applicationContext.getBean("father");
|
||||
assertTrue("Bean from root context", father != null);
|
||||
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
|
||||
|
||||
TestBean rod = (TestBean) this.applicationContext.getBean("rod");
|
||||
assertTrue("Bean from child context", "Rod".equals(rod.getName()));
|
||||
assertTrue("Bean has external reference", rod.getSpouse() == father);
|
||||
assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend"));
|
||||
|
||||
rod = (TestBean) this.root.getBean("rod");
|
||||
assertTrue("Bean from root context", "Roderick".equals(rod.getName()));
|
||||
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
|
||||
}
|
||||
|
||||
public void testInitializingBeanAndInitMethod() throws Exception {
|
||||
assertFalse(InitAndIB.constructed);
|
||||
InitAndIB iib = (InitAndIB) this.applicationContext.getBean("init-and-ib");
|
||||
assertTrue(InitAndIB.constructed);
|
||||
assertTrue(iib.afterPropertiesSetInvoked && iib.initMethodInvoked);
|
||||
assertTrue(!iib.destroyed && !iib.customDestroyed);
|
||||
this.applicationContext.close();
|
||||
assertTrue(!iib.destroyed && !iib.customDestroyed);
|
||||
ConfigurableApplicationContext parent = (ConfigurableApplicationContext) this.applicationContext.getParent();
|
||||
parent.close();
|
||||
assertTrue(iib.destroyed && iib.customDestroyed);
|
||||
parent.close();
|
||||
assertTrue(iib.destroyed && iib.customDestroyed);
|
||||
}
|
||||
|
||||
|
||||
public static class InitAndIB implements InitializingBean, DisposableBean {
|
||||
|
||||
public static boolean constructed;
|
||||
|
||||
public boolean afterPropertiesSetInvoked, initMethodInvoked, destroyed, customDestroyed;
|
||||
|
||||
public InitAndIB() {
|
||||
constructed = true;
|
||||
}
|
||||
|
||||
public void afterPropertiesSet() {
|
||||
if (this.initMethodInvoked)
|
||||
fail();
|
||||
this.afterPropertiesSetInvoked = true;
|
||||
}
|
||||
|
||||
/** Init method */
|
||||
public void customInit() throws ServletException {
|
||||
if (!this.afterPropertiesSetInvoked)
|
||||
fail();
|
||||
this.initMethodInvoked = true;
|
||||
}
|
||||
|
||||
public void destroy() {
|
||||
if (this.customDestroyed)
|
||||
fail();
|
||||
if (this.destroyed) {
|
||||
throw new IllegalStateException("Already destroyed");
|
||||
}
|
||||
this.destroyed = true;
|
||||
}
|
||||
|
||||
public void customDestroy() {
|
||||
if (!this.destroyed)
|
||||
fail();
|
||||
if (this.customDestroyed) {
|
||||
throw new IllegalStateException("Already customDestroyed");
|
||||
}
|
||||
this.customDestroyed = true;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,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;
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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.context;
|
||||
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
|
||||
import junit.framework.TestCase;
|
||||
|
||||
import org.springframework.mock.web.portlet.MockPortletRequest;
|
||||
|
||||
/**
|
||||
* @author Juergen Hoeller
|
||||
* @since 26.07.2006
|
||||
*/
|
||||
public class PortletWebRequestTests extends TestCase {
|
||||
|
||||
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]);
|
||||
}
|
||||
|
||||
public void testLocale() {
|
||||
MockPortletRequest portletRequest = new MockPortletRequest();
|
||||
portletRequest.addPreferredLocale(Locale.UK);
|
||||
|
||||
PortletWebRequest request = new PortletWebRequest(portletRequest);
|
||||
assertEquals(Locale.UK, request.getLocale());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -0,0 +1,6 @@
|
||||
code1=message1
|
||||
code2=message2
|
||||
|
||||
# Example taken from the javadocs for the java.text.MessageFormat class
|
||||
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
|
||||
message.format.example2=This is a test message in the message catalog with no args.
|
||||
@@ -0,0 +1,2 @@
|
||||
# Example taken from the javadocs for the java.text.MessageFormat class
|
||||
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on station number {0,number,integer}.
|
||||
@@ -0,0 +1,5 @@
|
||||
code1=message1
|
||||
|
||||
# Example taken from the javadocs for the java.text.MessageFormat class
|
||||
message.format.example1=At '{1,time}' on "{1,date}", there was "{2}" on planet {0,number,integer}.
|
||||
message.format.example2=This is a test message in the message catalog with no args.
|
||||
@@ -0,0 +1,6 @@
|
||||
<!-- Include snippet to be loaded via entity reference in applicationContext.xml -->
|
||||
|
||||
<bean id="father" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>yetanotherdummy</value></property>
|
||||
</bean>
|
||||
|
||||
@@ -0,0 +1,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>
|
||||
@@ -0,0 +1,2 @@
|
||||
code1=message1x
|
||||
code3=message3
|
||||
@@ -0,0 +1,3 @@
|
||||
father.name=Albert
|
||||
rod.age=31
|
||||
rod.name=Roderick
|
||||
@@ -0,0 +1,4 @@
|
||||
useCodeAsDefaultMessage=false
|
||||
message-file=context-messages
|
||||
objectName=test:service=myservice
|
||||
theme-base=org/springframework/web/portlet/context/WEB-INF/
|
||||
@@ -0,0 +1,24 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
|
||||
<property name="useCodeAsDefaultMessage">
|
||||
<value>${useCodeAsDefaultMessage}</value>
|
||||
</property>
|
||||
<property name="basenames">
|
||||
<list>
|
||||
<value>org/springframework/web/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>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
|
||||
<property name="basenamePrefix">
|
||||
<value>${theme-base}</value>
|
||||
</property>
|
||||
</bean>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,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>
|
||||
@@ -0,0 +1,59 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN" "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
|
||||
|
||||
<beans>
|
||||
|
||||
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
|
||||
<property name="basename"><value>org/springframework/web/context/WEB-INF/test-messages</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="themeSource" class="org.springframework.ui.context.support.ResourceBundleThemeSource">
|
||||
<property name="basenamePrefix"><value>org/springframework/web/context/WEB-INF/test-</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="aca" class="org.springframework.context.ACATester"/>
|
||||
|
||||
<bean id="aca-prototype" class="org.springframework.context.ACATester" scope="prototype"/>
|
||||
|
||||
<bean id="rod" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Rod</value></property>
|
||||
<property name="age"><value>31</value></property>
|
||||
<property name="spouse"><ref bean="father"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="testListener" class="org.springframework.context.TestListener"/>
|
||||
|
||||
<bean id="roderick" parent="rod">
|
||||
<property name="name"><value>Roderick</value></property>
|
||||
<property name="age"><value>31</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="kathy" class="org.springframework.beans.TestBean" scope="prototype"/>
|
||||
|
||||
<bean id="kerry" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>Kerry</value></property>
|
||||
<property name="age"><value>34</value></property>
|
||||
<property name="spouse"><ref local="rod"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="typeMismatch" class="org.springframework.beans.TestBean" scope="prototype">
|
||||
<property name="name"><value>typeMismatch</value></property>
|
||||
<property name="age"><value>34x</value></property>
|
||||
<property name="spouse"><ref local="rod"/></property>
|
||||
</bean>
|
||||
|
||||
<bean id="singletonFactory" class="org.springframework.beans.factory.DummyFactory">
|
||||
</bean>
|
||||
|
||||
<bean id="prototypeFactory" class="org.springframework.beans.factory.DummyFactory">
|
||||
<property name="singleton"><value>false</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="listenerVeto" class="org.springframework.beans.TestBean">
|
||||
<property name="name"><value>listenerVeto</value></property>
|
||||
<property name="age"><value>66</value></property>
|
||||
</bean>
|
||||
|
||||
<bean id="validEmpty" class="org.springframework.beans.TestBean"/>
|
||||
|
||||
</beans>
|
||||
@@ -0,0 +1,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());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.addPropertyValue("portletClass", MyPortlet.class);
|
||||
registerSingleton(PORTLET_WRAPPING_CONTROLLER_BEAN_NAME, PortletWrappingController.class, pvs);
|
||||
super.refresh();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,777 @@
|
||||
/*
|
||||
* 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.mvc.annotation;
|
||||
|
||||
import java.io.IOException;
|
||||
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.PortletContext;
|
||||
import javax.portlet.PortletMode;
|
||||
import javax.portlet.PortletRequest;
|
||||
import javax.portlet.PortletSession;
|
||||
import javax.portlet.RenderRequest;
|
||||
import javax.portlet.RenderResponse;
|
||||
import javax.portlet.UnavailableException;
|
||||
|
||||
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.context.StaticPortletApplicationContext;
|
||||
import org.springframework.web.portlet.mvc.AbstractController;
|
||||
|
||||
/**
|
||||
* @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, RenderRequest request, RenderResponse 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, RenderRequest request, RenderResponse 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().addPropertyValue("webBindingInitializer", new MyWebBindingInitializer());
|
||||
wac.registerBeanDefinition("handlerAdapter", adapterDef);
|
||||
wac.refresh();
|
||||
return wac;
|
||||
}
|
||||
|
||||
protected void render(ModelAndView mv, RenderRequest request, RenderResponse 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().addPropertyValue("webBindingInitializer", new MyWebBindingInitializer());
|
||||
adapterDef.getPropertyValues().addPropertyValue("customArgumentResolver", new MySpecialArgumentResolver());
|
||||
wac.registerBeanDefinition("handlerAdapter", adapterDef);
|
||||
wac.refresh();
|
||||
return wac;
|
||||
}
|
||||
protected void render(ModelAndView mv, RenderRequest request, RenderResponse 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, RenderRequest request, RenderResponse 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, RenderRequest request, RenderResponse 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 UnavailableException");
|
||||
}
|
||||
catch (UnavailableException 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());
|
||||
}
|
||||
|
||||
|
||||
@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, RenderRequest request, RenderResponse 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"));
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,566 @@
|
||||
/*
|
||||
* 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.util;
|
||||
|
||||
import static org.easymock.EasyMock.*;
|
||||
import static org.junit.Assert.*;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileNotFoundException;
|
||||
import java.util.Collections;
|
||||
import java.util.Enumeration;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Unit tests for {@link PortletUtils}.
|
||||
*
|
||||
* @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(expected=ClassCastException.class)
|
||||
public void testExposeRequestAttributesWithAttributesMapContainingBadKeyType() throws Exception {
|
||||
MockPortletRequest request = new MockPortletRequest();
|
||||
Map attributes = new HashMap<Object, Object>();
|
||||
attributes.put(new Object(), "bad key type");
|
||||
PortletUtils.exposeRequestAttributes(request, attributes);
|
||||
}
|
||||
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
@Test
|
||||
public void testExposeRequestAttributesSunnyDay() throws Exception {
|
||||
MockPortletRequest request = new MockPortletRequest();
|
||||
Map attributes = new HashMap<Object, Object>();
|
||||
attributes.put("ace", "Rick Hunter");
|
||||
attributes.put("mentor", "Roy Fokker");
|
||||
PortletUtils.exposeRequestAttributes(request, attributes);
|
||||
assertEquals("Obviously all of the entries in the supplied attributes Map are not being copied over (exposed)",
|
||||
attributes.size(), countElementsIn(request.getAttributeNames()));
|
||||
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 attributes = new HashMap<Object, Object>();
|
||||
PortletUtils.exposeRequestAttributes(request, attributes);
|
||||
assertEquals("Obviously all of the entries in the supplied attributes Map are not being copied over (exposed)",
|
||||
attributes.size(), countElementsIn(request.getAttributeNames()));
|
||||
}
|
||||
|
||||
@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);
|
||||
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 int countElementsIn(Enumeration<?> enumeration) {
|
||||
int count = 0;
|
||||
while (enumeration.hasMoreElements()) {
|
||||
enumeration.nextElement();
|
||||
++count;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
|
||||
private static final class NoPublicCtor {
|
||||
|
||||
private NoPublicCtor() {
|
||||
throw new IllegalArgumentException("Just for eclipse...");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user