moving unit tests from .testsuite -> .core, .beans, .web, .web.portlet, .web.servlet

This commit is contained in:
Chris Beams
2008-12-17 18:45:41 +00:00
parent 285be534df
commit 93e30a4fc5
138 changed files with 2932 additions and 966 deletions

View File

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

View File

@@ -1,86 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans.factory;
import junit.framework.Assert;
import org.springframework.beans.TestBean;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public abstract class AbstractListableBeanFactoryTests extends AbstractBeanFactoryTests {
/** Subclasses must initialize this */
protected ListableBeanFactory getListableBeanFactory() {
BeanFactory bf = getBeanFactory();
if (!(bf instanceof ListableBeanFactory)) {
throw new IllegalStateException("ListableBeanFactory required");
}
return (ListableBeanFactory) bf;
}
/**
* Subclasses can override this.
*/
public void testCount() {
assertCount(13);
}
protected final void assertCount(int count) {
String[] defnames = getListableBeanFactory().getBeanDefinitionNames();
Assert.assertTrue("We should have " + count + " beans, not " + defnames.length, defnames.length == count);
}
public void assertTestBeanCount(int count) {
String[] defNames = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, false);
Assert.assertTrue("We should have " + count + " beans for class org.springframework.beans.TestBean, not " +
defNames.length, defNames.length == count);
int countIncludingFactoryBeans = count + 2;
String[] names = getListableBeanFactory().getBeanNamesForType(TestBean.class, true, true);
Assert.assertTrue("We should have " + countIncludingFactoryBeans +
" beans for class org.springframework.beans.TestBean, not " + names.length,
names.length == countIncludingFactoryBeans);
}
public void testGetDefinitionsForNoSuchClass() {
String[] defnames = getListableBeanFactory().getBeanNamesForType(String.class);
Assert.assertTrue("No string definitions", defnames.length == 0);
}
/**
* Check that count refers to factory class, not bean class. (We don't know
* what type factories may return, and it may even change over time.)
*/
public void testGetCountForFactoryClass() {
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
Assert.assertTrue("Should have 2 factories, not " +
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length,
getListableBeanFactory().getBeanNamesForType(FactoryBean.class).length == 2);
}
public void testContainsBeanDefinition() {
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("rod"));
Assert.assertTrue(getListableBeanFactory().containsBeanDefinition("roderick"));
}
}

View File

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

View File

@@ -1,280 +0,0 @@
/*
* 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.ui;
import java.io.Serializable;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import junit.framework.TestCase;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.TestBean;
import org.springframework.test.AssertThrows;
import org.springframework.util.ClassUtils;
import org.springframework.util.StringUtils;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public final class ModelMapTests extends TestCase {
public void testNoArgCtorYieldsEmptyModel() throws Exception {
assertEquals(0, new ModelMap().size());
}
/*
* SPR-2185 - Null model assertion causes backwards compatibility issue
*/
public void testAddNullObjectWithExplicitKey() throws Exception {
ModelMap model = new ModelMap();
model.addAttribute("foo", null);
assertTrue(model.containsKey("foo"));
assertNull(model.get("foo"));
}
/*
* SPR-2185 - Null model assertion causes backwards compatibility issue
*/
public void testAddNullObjectViaCtorWithExplicitKey() throws Exception {
ModelMap model = new ModelMap("foo", null);
assertTrue(model.containsKey("foo"));
assertNull(model.get("foo"));
}
public void testNamedObjectCtor() throws Exception {
ModelMap model = new ModelMap("foo", "bing");
assertEquals(1, model.size());
String bing = (String) model.get("foo");
assertNotNull(bing);
assertEquals("bing", bing);
}
public void testUnnamedCtorScalar() throws Exception {
ModelMap model = new ModelMap("foo", "bing");
assertEquals(1, model.size());
String bing = (String) model.get("foo");
assertNotNull(bing);
assertEquals("bing", bing);
}
public void testOneArgCtorWithScalar() throws Exception {
ModelMap model = new ModelMap("bing");
assertEquals(1, model.size());
String string = (String) model.get("string");
assertNotNull(string);
assertEquals("bing", string);
}
public void testOneArgCtorWithNull() throws Exception {
new AssertThrows(IllegalArgumentException.class, "Null model arguments added without a name being explicitly supplied are not allowed.") {
public void test() throws Exception {
new ModelMap(null);
}
}.runTest();
}
public void testOneArgCtorWithCollection() throws Exception {
ModelMap model = new ModelMap(new String[]{"foo", "boing"});
assertEquals(1, model.size());
String[] strings = (String[]) model.get("stringList");
assertNotNull(strings);
assertEquals(2, strings.length);
assertEquals("foo", strings[0]);
assertEquals("boing", strings[1]);
}
public void testOneArgCtorWithEmptyCollection() throws Exception {
ModelMap model = new ModelMap(new HashSet());
// must not add if collection is empty...
assertEquals(0, model.size());
}
public void testAddObjectWithNull() throws Exception {
new AssertThrows(IllegalArgumentException.class, "Null model arguments added without a name being explicitly supplied are not allowed.") {
public void test() throws Exception {
ModelMap model = new ModelMap();
model.addAttribute(null);
}
}.runTest();
}
public void testAddObjectWithEmptyArray() throws Exception {
ModelMap model = new ModelMap(new int[]{});
assertEquals(1, model.size());
int[] ints = (int[]) model.get("intList");
assertNotNull(ints);
assertEquals(0, ints.length);
}
public void testAddAllObjectsWithNullMap() throws Exception {
ModelMap model = new ModelMap();
model.addAllAttributes((Map) null);
assertEquals(0, model.size());
}
public void testAddAllObjectsWithNullCollection() throws Exception {
ModelMap model = new ModelMap();
model.addAllAttributes((Collection) null);
assertEquals(0, model.size());
}
public void testAddAllObjectsWithSparseArrayList() throws Exception {
new AssertThrows(IllegalArgumentException.class, "Null model arguments added without a name being explicitly supplied are not allowed.") {
public void test() throws Exception {
ModelMap model = new ModelMap();
ArrayList list = new ArrayList();
list.add("bing");
list.add(null);
model.addAllAttributes(list);
}
}.runTest();
}
public void testAddMap() throws Exception {
Map map = new HashMap();
map.put("one", "one-value");
map.put("two", "two-value");
ModelMap model = new ModelMap();
model.addAttribute(map);
assertEquals(1, model.size());
String key = StringUtils.uncapitalize(ClassUtils.getShortName(map.getClass()));
assertTrue(model.containsKey(key));
}
public void testAddObjectNoKeyOfSameTypeOverrides() throws Exception {
ModelMap model = new ModelMap();
model.addAttribute("foo");
model.addAttribute("bar");
assertEquals(1, model.size());
String bar = (String) model.get("string");
assertEquals("bar", bar);
}
public void testAddListOfTheSameObjects() throws Exception {
List beans = new ArrayList();
beans.add(new TestBean("one"));
beans.add(new TestBean("two"));
beans.add(new TestBean("three"));
ModelMap model = new ModelMap();
model.addAllAttributes(beans);
assertEquals(1, model.size());
}
public void testMergeMapWithOverriding() throws Exception {
Map beans = new HashMap();
beans.put("one", new TestBean("one"));
beans.put("two", new TestBean("two"));
beans.put("three", new TestBean("three"));
ModelMap model = new ModelMap();
model.put("one", new TestBean("oneOld"));
model.mergeAttributes(beans);
assertEquals(3, model.size());
assertEquals("oneOld", ((TestBean) model.get("one")).getName());
}
public void testInnerClass() throws Exception {
ModelMap map = new ModelMap();
SomeInnerClass inner = new SomeInnerClass();
map.addAttribute(inner);
assertSame(inner, map.get("someInnerClass"));
}
public void testInnerClassWithTwoUpperCaseLetters() throws Exception {
ModelMap map = new ModelMap();
UKInnerClass inner = new UKInnerClass();
map.addAttribute(inner);
assertSame(inner, map.get("UKInnerClass"));
}
public void testAopCglibProxy() throws Exception {
ModelMap map = new ModelMap();
ProxyFactory factory = new ProxyFactory();
Date date = new Date();
factory.setTarget(date);
factory.setProxyTargetClass(true);
map.addAttribute(factory.getProxy());
assertTrue(map.containsKey("date"));
assertEquals(date, map.get("date"));
}
public void testAopJdkProxy() throws Exception {
ModelMap map = new ModelMap();
ProxyFactory factory = new ProxyFactory();
Map target = new HashMap();
factory.setTarget(target);
factory.addInterface(Map.class);
Object proxy = factory.getProxy();
map.addAttribute(proxy);
assertSame(proxy, map.get("map"));
}
public void testAopJdkProxyWithMultipleInterfaces() throws Exception {
ModelMap map = new ModelMap();
Map target = new HashMap();
ProxyFactory factory = new ProxyFactory();
factory.setTarget(target);
factory.addInterface(Serializable.class);
factory.addInterface(Cloneable.class);
factory.addInterface(Comparable.class);
factory.addInterface(Map.class);
Object proxy = factory.getProxy();
map.addAttribute(proxy);
assertSame(proxy, map.get("map"));
}
public void testAopJdkProxyWithDetectedInterfaces() throws Exception {
ModelMap map = new ModelMap();
Map target = new HashMap();
ProxyFactory factory = new ProxyFactory(target);
Object proxy = factory.getProxy();
map.addAttribute(proxy);
assertSame(proxy, map.get("map"));
}
public void testRawJdkProxy() throws Exception {
ModelMap map = new ModelMap();
Object proxy = Proxy.newProxyInstance(
getClass().getClassLoader(),
new Class[] {Map.class},
new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) {
return "proxy";
}
});
map.addAttribute(proxy);
assertSame(proxy, map.get("map"));
}
private static class SomeInnerClass {
}
private static class UKInnerClass {
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ui.jasperreports;
/**
* @author Rob Harrop
*/
public class PersonBean {
private int id;
private String name;
private String street;
private String city;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.ui.jasperreports;
/**
* @author Rob Harrop
*/
public class ProductBean {
private int id;
private String name;
private float quantity;
private float price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getQuantity() {
return quantity;
}
public void setQuantity(float quantity) {
this.quantity = quantity;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
}

View File

@@ -1,320 +0,0 @@
/*
* 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.util;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.IOther;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
/**
* @author Colin Sampaleanu
* @author Juergen Hoeller
* @author Rob Harrop
* @author Rick Evans
*/
public class ClassUtilsTests extends TestCase {
public void setUp() {
InnerClass.noArgCalled = false;
InnerClass.argCalled = false;
InnerClass.overloadedCalled = false;
}
public void testIsPresent() throws Exception {
assertTrue(ClassUtils.isPresent("java.lang.String"));
assertFalse(ClassUtils.isPresent("java.lang.MySpecialString"));
}
public void testForName() throws ClassNotFoundException {
assertEquals(String.class, ClassUtils.forName("java.lang.String"));
assertEquals(String[].class, ClassUtils.forName("java.lang.String[]"));
assertEquals(String[].class, ClassUtils.forName(String[].class.getName()));
assertEquals(String[][].class, ClassUtils.forName(String[][].class.getName()));
assertEquals(String[][][].class, ClassUtils.forName(String[][][].class.getName()));
assertEquals(TestBean.class, ClassUtils.forName("org.springframework.beans.TestBean"));
assertEquals(TestBean[].class, ClassUtils.forName("org.springframework.beans.TestBean[]"));
assertEquals(TestBean[].class, ClassUtils.forName(TestBean[].class.getName()));
assertEquals(TestBean[][].class, ClassUtils.forName("org.springframework.beans.TestBean[][]"));
assertEquals(TestBean[][].class, ClassUtils.forName(TestBean[][].class.getName()));
}
public void testForNameWithPrimitiveClasses() throws ClassNotFoundException {
assertEquals(boolean.class, ClassUtils.forName("boolean"));
assertEquals(byte.class, ClassUtils.forName("byte"));
assertEquals(char.class, ClassUtils.forName("char"));
assertEquals(short.class, ClassUtils.forName("short"));
assertEquals(int.class, ClassUtils.forName("int"));
assertEquals(long.class, ClassUtils.forName("long"));
assertEquals(float.class, ClassUtils.forName("float"));
assertEquals(double.class, ClassUtils.forName("double"));
}
public void testForNameWithPrimitiveArrays() throws ClassNotFoundException {
assertEquals(boolean[].class, ClassUtils.forName("boolean[]"));
assertEquals(byte[].class, ClassUtils.forName("byte[]"));
assertEquals(char[].class, ClassUtils.forName("char[]"));
assertEquals(short[].class, ClassUtils.forName("short[]"));
assertEquals(int[].class, ClassUtils.forName("int[]"));
assertEquals(long[].class, ClassUtils.forName("long[]"));
assertEquals(float[].class, ClassUtils.forName("float[]"));
assertEquals(double[].class, ClassUtils.forName("double[]"));
}
public void testForNameWithPrimitiveArraysInternalName() throws ClassNotFoundException {
assertEquals(boolean[].class, ClassUtils.forName(boolean[].class.getName()));
assertEquals(byte[].class, ClassUtils.forName(byte[].class.getName()));
assertEquals(char[].class, ClassUtils.forName(char[].class.getName()));
assertEquals(short[].class, ClassUtils.forName(short[].class.getName()));
assertEquals(int[].class, ClassUtils.forName(int[].class.getName()));
assertEquals(long[].class, ClassUtils.forName(long[].class.getName()));
assertEquals(float[].class, ClassUtils.forName(float[].class.getName()));
assertEquals(double[].class, ClassUtils.forName(double[].class.getName()));
}
public void testGetShortName() {
String className = ClassUtils.getShortName(getClass());
assertEquals("Class name did not match", "ClassUtilsTests", className);
}
public void testGetShortNameForObjectArrayClass() {
String className = ClassUtils.getShortName(Object[].class);
assertEquals("Class name did not match", "Object[]", className);
}
public void testGetShortNameForMultiDimensionalObjectArrayClass() {
String className = ClassUtils.getShortName(Object[][].class);
assertEquals("Class name did not match", "Object[][]", className);
}
public void testGetShortNameForPrimitiveArrayClass() {
String className = ClassUtils.getShortName(byte[].class);
assertEquals("Class name did not match", "byte[]", className);
}
public void testGetShortNameForMultiDimensionalPrimitiveArrayClass() {
String className = ClassUtils.getShortName(byte[][][].class);
assertEquals("Class name did not match", "byte[][][]", className);
}
public void testGetShortNameForInnerClass() {
String className = ClassUtils.getShortName(InnerClass.class);
assertEquals("Class name did not match", "ClassUtilsTests.InnerClass", className);
}
public void testGetShortNameForCglibClass() {
TestBean tb = new TestBean();
ProxyFactory pf = new ProxyFactory();
pf.setTarget(tb);
pf.setProxyTargetClass(true);
TestBean proxy = (TestBean) pf.getProxy();
String className = ClassUtils.getShortName(proxy.getClass());
assertEquals("Class name did not match", "TestBean", className);
}
public void testGetShortNameAsProperty() {
String shortName = ClassUtils.getShortNameAsProperty(this.getClass());
assertEquals("Class name did not match", "classUtilsTests", shortName);
}
public void testGetClassFileName() {
assertEquals("String.class", ClassUtils.getClassFileName(String.class));
assertEquals("ClassUtilsTests.class", ClassUtils.getClassFileName(getClass()));
}
public void testGetPackageName() {
assertEquals("java.lang", ClassUtils.getPackageName(String.class));
assertEquals(getClass().getPackage().getName(), ClassUtils.getPackageName(getClass()));
}
public void testGetQualifiedName() {
String className = ClassUtils.getQualifiedName(getClass());
assertEquals("Class name did not match", "org.springframework.util.ClassUtilsTests", className);
}
public void testGetQualifiedNameForObjectArrayClass() {
String className = ClassUtils.getQualifiedName(Object[].class);
assertEquals("Class name did not match", "java.lang.Object[]", className);
}
public void testGetQualifiedNameForMultiDimensionalObjectArrayClass() {
String className = ClassUtils.getQualifiedName(Object[][].class);
assertEquals("Class name did not match", "java.lang.Object[][]", className);
}
public void testGetQualifiedNameForPrimitiveArrayClass() {
String className = ClassUtils.getQualifiedName(byte[].class);
assertEquals("Class name did not match", "byte[]", className);
}
public void testGetQualifiedNameForMultiDimensionalPrimitiveArrayClass() {
String className = ClassUtils.getQualifiedName(byte[][].class);
assertEquals("Class name did not match", "byte[][]", className);
}
public void testHasMethod() throws Exception {
assertTrue(ClassUtils.hasMethod(Collection.class, "size", null));
assertTrue(ClassUtils.hasMethod(Collection.class, "remove", new Class[] {Object.class}));
assertFalse(ClassUtils.hasMethod(Collection.class, "remove", null));
assertFalse(ClassUtils.hasMethod(Collection.class, "someOtherMethod", null));
}
public void testGetMethodIfAvailable() throws Exception {
Method method = ClassUtils.getMethodIfAvailable(Collection.class, "size", null);
assertNotNull(method);
assertEquals("size", method.getName());
method = ClassUtils.getMethodIfAvailable(Collection.class, "remove", new Class[] {Object.class});
assertNotNull(method);
assertEquals("remove", method.getName());
assertNull(ClassUtils.getMethodIfAvailable(Collection.class, "remove", null));
assertNull(ClassUtils.getMethodIfAvailable(Collection.class, "someOtherMethod", null));
}
public void testGetMethodCountForName() {
assertEquals("Verifying number of overloaded 'print' methods for OverloadedMethodsClass.", 2,
ClassUtils.getMethodCountForName(OverloadedMethodsClass.class, "print"));
assertEquals("Verifying number of overloaded 'print' methods for SubOverloadedMethodsClass.", 4,
ClassUtils.getMethodCountForName(SubOverloadedMethodsClass.class, "print"));
}
public void testCountOverloadedMethods() {
assertFalse(ClassUtils.hasAtLeastOneMethodWithName(TestBean.class, "foobar"));
// no args
assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestBean.class, "hashCode"));
// matches although it takes an arg
assertTrue(ClassUtils.hasAtLeastOneMethodWithName(TestBean.class, "setAge"));
}
public void testNoArgsStaticMethod() throws IllegalAccessException, InvocationTargetException {
Method method = ClassUtils.getStaticMethod(InnerClass.class, "staticMethod", (Class[]) null);
method.invoke(null, (Object[]) null);
assertTrue("no argument method was not invoked.",
InnerClass.noArgCalled);
}
public void testArgsStaticMethod() throws IllegalAccessException, InvocationTargetException {
Method method = ClassUtils.getStaticMethod(InnerClass.class, "argStaticMethod",
new Class[] {String.class});
method.invoke(null, new Object[] {"test"});
assertTrue("argument method was not invoked.", InnerClass.argCalled);
}
public void testOverloadedStaticMethod() throws IllegalAccessException, InvocationTargetException {
Method method = ClassUtils.getStaticMethod(InnerClass.class, "staticMethod",
new Class[] {String.class});
method.invoke(null, new Object[] {"test"});
assertTrue("argument method was not invoked.",
InnerClass.overloadedCalled);
}
public void testClassPackageAsResourcePath() {
String result = ClassUtils.classPackageAsResourcePath(Proxy.class);
assertTrue(result.equals("java/lang/reflect"));
}
public void testAddResourcePathToPackagePath() {
String result = "java/lang/reflect/xyzabc.xml";
assertEquals(result, ClassUtils.addResourcePathToPackagePath(Proxy.class, "xyzabc.xml"));
assertEquals(result, ClassUtils.addResourcePathToPackagePath(Proxy.class, "/xyzabc.xml"));
assertEquals("java/lang/reflect/a/b/c/d.xml",
ClassUtils.addResourcePathToPackagePath(Proxy.class, "a/b/c/d.xml"));
}
public void testGetAllInterfaces() {
DerivedTestBean testBean = new DerivedTestBean();
List ifcs = Arrays.asList(ClassUtils.getAllInterfaces(testBean));
assertEquals("Correct number of interfaces", 7, ifcs.size());
assertTrue("Contains Serializable", ifcs.contains(Serializable.class));
assertTrue("Contains ITestBean", ifcs.contains(ITestBean.class));
assertTrue("Contains IOther", ifcs.contains(IOther.class));
}
public void testClassNamesToString() {
List ifcs = new LinkedList();
ifcs.add(Serializable.class);
ifcs.add(Runnable.class);
assertEquals("[interface java.io.Serializable, interface java.lang.Runnable]", ifcs.toString());
assertEquals("[java.io.Serializable, java.lang.Runnable]", ClassUtils.classNamesToString(ifcs));
List classes = new LinkedList();
classes.add(LinkedList.class);
classes.add(Integer.class);
assertEquals("[class java.util.LinkedList, class java.lang.Integer]", classes.toString());
assertEquals("[java.util.LinkedList, java.lang.Integer]", ClassUtils.classNamesToString(classes));
assertEquals("[interface java.util.List]", Collections.singletonList(List.class).toString());
assertEquals("[java.util.List]", ClassUtils.classNamesToString(List.class));
assertEquals("[]", Collections.EMPTY_LIST.toString());
assertEquals("[]", ClassUtils.classNamesToString(Collections.EMPTY_LIST));
}
public static class InnerClass {
static boolean noArgCalled;
static boolean argCalled;
static boolean overloadedCalled;
public static void staticMethod() {
noArgCalled = true;
}
public static void staticMethod(String anArg) {
overloadedCalled = true;
}
public static void argStaticMethod(String anArg) {
argCalled = true;
}
}
private static class OverloadedMethodsClass {
public void print(String messages) {
/* no-op */
}
public void print(String[] messages) {
/* no-op */
}
}
private static class SubOverloadedMethodsClass extends OverloadedMethodsClass{
public void print(String header, String[] messages) {
/* no-op */
}
void print(String header, String[] messages, String footer) {
/* no-op */
}
}
}

View File

@@ -1,61 +0,0 @@
/*
* 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.util;
import java.lang.reflect.Type;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import junit.framework.TestCase;
/**
* @author Juergen Hoeller
*/
public class TypeUtilsTests extends TestCase {
public static List<Object> objects;
public static List<? extends Object> openObjects;
public static List<String> strings;
public void testClasses() {
assertTrue(TypeUtils.isAssignable(Object.class, Object.class));
assertTrue(TypeUtils.isAssignable(Object.class, String.class));
assertFalse(TypeUtils.isAssignable(String.class, Object.class));
assertTrue(TypeUtils.isAssignable(List.class, List.class));
assertTrue(TypeUtils.isAssignable(List.class, LinkedList.class));
assertFalse(TypeUtils.isAssignable(List.class, Collection.class));
assertFalse(TypeUtils.isAssignable(List.class, HashSet.class));
}
public void testParameterizedTypes() throws Exception {
Type objectsType = getClass().getField("objects").getGenericType();
Type openObjectsType = getClass().getField("openObjects").getGenericType();
Type stringsType = getClass().getField("strings").getGenericType();
assertTrue(TypeUtils.isAssignable(objectsType, objectsType));
assertTrue(TypeUtils.isAssignable(openObjectsType, openObjectsType));
assertTrue(TypeUtils.isAssignable(stringsType, stringsType));
assertTrue(TypeUtils.isAssignable(openObjectsType, objectsType));
assertTrue(TypeUtils.isAssignable(openObjectsType, stringsType));
assertFalse(TypeUtils.isAssignable(stringsType, objectsType));
assertFalse(TypeUtils.isAssignable(objectsType, stringsType));
}
}

View File

@@ -1,179 +0,0 @@
/*
* 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.util.comparator;
import java.util.Comparator;
import junit.framework.TestCase;
import org.springframework.beans.support.PropertyComparator;
/**
* @author Keith Donald
*/
public class ComparatorTests extends TestCase {
public void testComparableComparator() {
Comparator c = new ComparableComparator();
String s1 = "abc";
String s2 = "cde";
assertTrue(c.compare(s1, s2) < 0);
}
public void testComparableComparatorIllegalArgs() {
Comparator c = new ComparableComparator();
Object o1 = new Object();
Object o2 = new Object();
try {
c.compare(o1, o2);
}
catch (ClassCastException e) {
return;
}
fail("Comparator should have thrown a cce");
}
public void testBooleanComparatorTrueLow() {
Comparator c = BooleanComparator.TRUE_LOW;
assertTrue(c.compare(new Boolean(true), new Boolean(false)) < 0);
}
public void testBooleanComparatorTrueHigh() {
Comparator c = BooleanComparator.TRUE_HIGH;
assertTrue(c.compare(new Boolean(true), new Boolean(false)) > 0);
assertTrue(c.compare(Boolean.TRUE, Boolean.TRUE) == 0);
}
public void testPropertyComparator() {
Dog dog = new Dog();
dog.setNickName("mace");
Dog dog2 = new Dog();
dog2.setNickName("biscy");
PropertyComparator c = new PropertyComparator("nickName", false, true);
assertTrue(c.compare(dog, dog2) > 0);
assertTrue(c.compare(dog, dog) == 0);
assertTrue(c.compare(dog2, dog) < 0);
}
public void testPropertyComparatorNulls() {
Dog dog = new Dog();
Dog dog2 = new Dog();
PropertyComparator c = new PropertyComparator("nickName", false, true);
assertTrue(c.compare(dog, dog2) == 0);
}
public void testNullSafeComparatorNullsLow() {
Comparator c = NullSafeComparator.NULLS_LOW;
assertTrue(c.compare(null, "boo") < 0);
}
public void testNullSafeComparatorNullsHigh() {
Comparator c = NullSafeComparator.NULLS_HIGH;
assertTrue(c.compare(null, "boo") > 0);
assertTrue(c.compare(null, null) == 0);
}
public void testCompoundComparatorEmpty() {
Comparator c = new CompoundComparator();
try {
c.compare("foo", "bar");
}
catch (IllegalStateException e) {
return;
}
fail("illegal state should've been thrown on empty list");
}
public void testCompoundComparator() {
CompoundComparator c = new CompoundComparator();
c.addComparator(new PropertyComparator("lastName", false, true));
Dog dog1 = new Dog();
dog1.setFirstName("macy");
dog1.setLastName("grayspots");
Dog dog2 = new Dog();
dog2.setFirstName("biscuit");
dog2.setLastName("grayspots");
assertTrue(c.compare(dog1, dog2) == 0);
c.addComparator(new PropertyComparator("firstName", false, true));
assertTrue(c.compare(dog1, dog2) > 0);
dog2.setLastName("konikk dog");
assertTrue(c.compare(dog2, dog1) > 0);
}
public void testCompoundComparatorInvert() {
CompoundComparator c = new CompoundComparator();
c.addComparator(new PropertyComparator("lastName", false, true));
c.addComparator(new PropertyComparator("firstName", false, true));
Dog dog1 = new Dog();
dog1.setFirstName("macy");
dog1.setLastName("grayspots");
Dog dog2 = new Dog();
dog2.setFirstName("biscuit");
dog2.setLastName("grayspots");
assertTrue(c.compare(dog1, dog2) > 0);
c.invertOrder();
assertTrue(c.compare(dog1, dog2) < 0);
}
private static class Dog implements Comparable {
private String nickName;
private String firstName;
private String lastName;
public int compareTo(Object o) {
return nickName.compareTo(((Dog)o).nickName);
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
}

View File

@@ -1,181 +0,0 @@
/*
* 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.validation;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
import org.springframework.test.AssertThrows;
/**
* @author Juergen Hoeller
* @author Rick Evans
* @since 08.10.2004
*/
public class ValidationUtilsTests extends TestCase {
public void testInvokeValidatorWithNullValidator() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TestBean tb = new TestBean();
Errors errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.invokeValidator(null, tb, errors);
}
}.runTest();
}
public void testInvokeValidatorWithNullErrors() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
TestBean tb = new TestBean();
ValidationUtils.invokeValidator(new EmptyValidator(), tb, null);
}
}.runTest();
}
public void testInvokeValidatorSunnyDay() throws Exception {
TestBean tb = new TestBean();
Errors errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.invokeValidator(new EmptyValidator(), tb, errors);
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY", errors.getFieldError("name").getCode());
}
public void testValidationUtilsSunnyDay() throws Exception {
TestBean tb = new TestBean("");
Validator testValidator = new EmptyValidator();
tb.setName(" ");
Errors errors = new BeanPropertyBindingResult(tb, "tb");
testValidator.validate(tb, errors);
assertFalse(errors.hasFieldErrors("name"));
tb.setName("Roddy");
errors = new BeanPropertyBindingResult(tb, "tb");
testValidator.validate(tb, errors);
assertFalse(errors.hasFieldErrors("name"));
}
public void testValidationUtilsNull() throws Exception {
TestBean tb = new TestBean();
Errors errors = new BeanPropertyBindingResult(tb, "tb");
Validator testValidator = new EmptyValidator();
testValidator.validate(tb, errors);
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY", errors.getFieldError("name").getCode());
}
public void testValidationUtilsEmpty() throws Exception {
TestBean tb = new TestBean("");
Errors errors = new BeanPropertyBindingResult(tb, "tb");
Validator testValidator = new EmptyValidator();
testValidator.validate(tb, errors);
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY", errors.getFieldError("name").getCode());
}
public void testValidationUtilsEmptyVariants() {
TestBean tb = new TestBean();
Errors errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"});
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
assertEquals("arg", errors.getFieldError("name").getArguments()[0]);
errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}, "msg");
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
assertEquals("arg", errors.getFieldError("name").getArguments()[0]);
assertEquals("msg", errors.getFieldError("name").getDefaultMessage());
}
public void testValidationUtilsEmptyOrWhitespace() throws Exception {
TestBean tb = new TestBean();
Validator testValidator = new EmptyOrWhitespaceValidator();
// Test null
Errors errors = new BeanPropertyBindingResult(tb, "tb");
testValidator.validate(tb, errors);
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
// Test empty String
tb.setName("");
errors = new BeanPropertyBindingResult(tb, "tb");
testValidator.validate(tb, errors);
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
// Test whitespace String
tb.setName(" ");
errors = new BeanPropertyBindingResult(tb, "tb");
testValidator.validate(tb, errors);
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
// Test OK
tb.setName("Roddy");
errors = new BeanPropertyBindingResult(tb, "tb");
testValidator.validate(tb, errors);
assertFalse(errors.hasFieldErrors("name"));
}
public void testValidationUtilsEmptyOrWhitespaceVariants() {
TestBean tb = new TestBean();
tb.setName(" ");
Errors errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"});
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
assertEquals("arg", errors.getFieldError("name").getArguments()[0]);
errors = new BeanPropertyBindingResult(tb, "tb");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", new Object[] {"arg"}, "msg");
assertTrue(errors.hasFieldErrors("name"));
assertEquals("EMPTY_OR_WHITESPACE", errors.getFieldError("name").getCode());
assertEquals("arg", errors.getFieldError("name").getArguments()[0]);
assertEquals("msg", errors.getFieldError("name").getDefaultMessage());
}
private static class EmptyValidator implements Validator {
public boolean supports(Class clazz) {
return TestBean.class.isAssignableFrom(clazz);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "name", "EMPTY", "You must enter a name!");
}
}
private static class EmptyOrWhitespaceValidator implements Validator {
public boolean supports(Class clazz) {
return TestBean.class.isAssignableFrom(clazz);
}
public void validate(Object obj, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "EMPTY_OR_WHITESPACE", "You must enter a name!");
}
}
}

View File

@@ -1 +0,0 @@
typeMismatch=Field {0} did not have correct type

View File

@@ -1,2 +0,0 @@
typeMismatch=Field {0} did not have correct type
age=Age

View File

@@ -1,2 +0,0 @@
typeMismatch=Field {0} did not have correct type
person.age=Person Age

View File

@@ -1,199 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.filter;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class CharacterEncodingFilterTests extends TestCase {
private static final String FILTER_NAME = "boot";
private static final String ENCODING = "UTF-8";
public void testForceAlwaysSetsEncoding() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockControl mockResponse = MockControl.createControl(HttpServletResponse.class);
HttpServletResponse response = (HttpServletResponse) mockResponse.getMock();
response.setCharacterEncoding(ENCODING);
mockResponse.setVoidCallable();
mockResponse.replay();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(true);
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockResponse.verify();
mockFilter.verify();
}
public void testEncodingIfEmptyAndNotForced() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(null);
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setForceEncoding(false);
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
public void testDoesNowtIfEncodingIsNotEmptyAndNotForced() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(ENCODING);
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.init(new MockFilterConfig(FILTER_NAME));
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
public void testWithBeanInitialization() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(null);
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(FILTER_NAME + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.setBeanName(FILTER_NAME);
filter.setServletContext(new MockServletContext());
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
public void testWithIncompleteInitialization() throws Exception {
MockControl mockRequest = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) mockRequest.getMock();
request.getCharacterEncoding();
mockRequest.setReturnValue(null);
request.setCharacterEncoding(ENCODING);
mockRequest.setVoidCallable();
request.getAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setReturnValue(null);
request.setAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX, Boolean.TRUE);
mockRequest.setVoidCallable();
request.removeAttribute(CharacterEncodingFilter.class.getName() + OncePerRequestFilter.ALREADY_FILTERED_SUFFIX);
mockRequest.setVoidCallable();
mockRequest.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
MockControl mockFilter = MockControl.createControl(FilterChain.class);
FilterChain filterChain = (FilterChain) mockFilter.getMock();
filterChain.doFilter(request, response);
mockFilter.replay();
CharacterEncodingFilter filter = new CharacterEncodingFilter();
filter.setEncoding(ENCODING);
filter.doFilter(request, response, filterChain);
mockRequest.verify();
mockFilter.verify();
}
}

View File

@@ -1,170 +0,0 @@
/* Copyright 2004, 2005 Acegi Technology Pty Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import junit.framework.TestCase;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
/**
* @author Juergen Hoeller
* @since 08.05.2005
*/
public class DelegatingFilterProxyTests extends TestCase {
public void testDelegatingFilterProxy() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
public void testDelegatingFilterProxyWithFilterName() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc, "targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
public void testDelegatingFilterProxyWithLazyContextStartup() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertNull(targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
public void testDelegatingFilterProxyWithTargetFilterLifecycle() throws ServletException, IOException {
ServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(sc);
wac.registerSingleton("targetFilter", MockFilter.class);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
MockFilter targetFilter = (MockFilter) wac.getBean("targetFilter");
MockFilterConfig proxyConfig = new MockFilterConfig(sc);
proxyConfig.addInitParameter("targetBeanName", "targetFilter");
proxyConfig.addInitParameter("targetFilterLifecycle", "true");
DelegatingFilterProxy filterProxy = new DelegatingFilterProxy();
filterProxy.init(proxyConfig);
assertEquals(proxyConfig, targetFilter.filterConfig);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
filterProxy.doFilter(request, response, null);
assertEquals(proxyConfig, targetFilter.filterConfig);
assertEquals(Boolean.TRUE, request.getAttribute("called"));
filterProxy.destroy();
assertNull(targetFilter.filterConfig);
}
public static class MockFilter implements Filter {
public FilterConfig filterConfig;
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
request.setAttribute("called", Boolean.TRUE);
}
public void destroy() {
this.filterConfig = null;
}
}
}

View File

@@ -1,99 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import junit.framework.TestCase;
import org.springframework.mock.web.MockFilterConfig;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class RequestContextFilterTests extends TestCase {
public void testHappyPath() throws Exception {
testFilterInvocation(null);
}
public void testWithException() throws Exception {
testFilterInvocation(new ServletException());
}
public void testFilterInvocation(final ServletException sex) throws Exception {
final MockHttpServletRequest req = new MockHttpServletRequest();
req.setAttribute("myAttr", "myValue");
final MockHttpServletResponse resp = new MockHttpServletResponse();
// Expect one invocation by the filter being tested
class DummyFilterChain implements FilterChain {
public int invocations = 0;
public void doFilter(ServletRequest req, ServletResponse resp) throws IOException, ServletException {
++invocations;
if (invocations == 1) {
assertSame("myValue",
RequestContextHolder.currentRequestAttributes().getAttribute("myAttr", RequestAttributes.SCOPE_REQUEST));
if (sex != null) {
throw sex;
}
}
else {
throw new IllegalStateException("Too many invocations");
}
}
};
DummyFilterChain fc = new DummyFilterChain();
MockFilterConfig mfc = new MockFilterConfig(new MockServletContext(), "foo");
RequestContextFilter rbf = new RequestContextFilter();
rbf.init(mfc);
try {
rbf.doFilter(req, resp, fc);
if (sex != null) {
fail();
}
}
catch (ServletException ex) {
assertNotNull(sex);
}
try {
RequestContextHolder.currentRequestAttributes();
fail();
}
catch (IllegalStateException ex) {
// Ok
}
assertEquals(1, fc.invocations);
}
}

View File

@@ -1,93 +0,0 @@
/*
* Copyright ${YEAR} the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.filter;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.util.FileCopyUtils;
public class ShallowEtagHeaderFilterTest {
private ShallowEtagHeaderFilter filter;
@Before
public void createFilter() throws Exception {
filter = new ShallowEtagHeaderFilter();
}
@Test
public void filterNoMatch() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
MockHttpServletResponse response = new MockHttpServletResponse();
final byte[] responseBody = "Hello World".getBytes("UTF-8");
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid request passed", request, filterRequest);
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
}
};
filter.doFilter(request, response, filterChain);
assertEquals("Invalid status", 200, response.getStatus());
assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
assertTrue("Invalid Content-Length header", response.getContentLength() > 0);
assertArrayEquals("Invalid content", responseBody, response.getContentAsByteArray());
}
@Test
public void filterMatch() throws Exception {
final MockHttpServletRequest request = new MockHttpServletRequest("GET", "/hotels");
String etag = "\"0b10a8db164e0754105b7a99be72e3fe5\"";
request.addHeader("If-None-Match", etag);
MockHttpServletResponse response = new MockHttpServletResponse();
FilterChain filterChain = new FilterChain() {
public void doFilter(ServletRequest filterRequest, ServletResponse filterResponse)
throws IOException, ServletException {
assertEquals("Invalid request passed", request, filterRequest);
((HttpServletResponse) filterResponse).setStatus(HttpServletResponse.SC_OK);
byte[] responseBody = "Hello World".getBytes("UTF-8");
FileCopyUtils.copy(responseBody, filterResponse.getOutputStream());
}
};
filter.doFilter(request, response, filterChain);
assertEquals("Invalid status", 304, response.getStatus());
assertEquals("Invalid ETag header", "\"0b10a8db164e0754105b7a99be72e3fe5\"", response.getHeader("ETag"));
assertEquals("Invalid Content-Length header", 0, response.getContentLength());
assertArrayEquals("Invalid content", new byte[0], response.getContentAsByteArray());
}
}

View File

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

View File

@@ -1,989 +0,0 @@
/*
* 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();
}
}

View File

@@ -1,177 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
/**
* @author Mark Fisher
*/
public class GenericPortletBeanTests extends TestCase {
public void testInitParameterSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testValue = "testValue";
portletConfig.addInitParameter("testParam", testValue);
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertEquals(testValue, portletBean.getTestParam());
}
public void testInitParameterNotSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
portletBean.init(portletConfig);
assertNull(portletBean.getTestParam());
}
public void testMultipleInitParametersSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testValue = "testValue";
String anotherValue = "anotherValue";
portletConfig.addInitParameter("testParam", testValue);
portletConfig.addInitParameter("anotherParam", anotherValue);
portletConfig.addInitParameter("unknownParam", "unknownValue");
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
assertNull(portletBean.getAnotherParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertNotNull(portletBean.getAnotherParam());
assertEquals(testValue, portletBean.getTestParam());
assertEquals(anotherValue, portletBean.getAnotherParam());
}
public void testMultipleInitParametersOnlyOneSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testValue = "testValue";
portletConfig.addInitParameter("testParam", testValue);
portletConfig.addInitParameter("unknownParam", "unknownValue");
TestPortletBean portletBean = new TestPortletBean();
assertNull(portletBean.getTestParam());
assertNull(portletBean.getAnotherParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertEquals(testValue, portletBean.getTestParam());
assertNull(portletBean.getAnotherParam());
}
public void testRequiredInitParameterSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty(testParam);
assertNull(portletBean.getTestParam());
portletBean.init(portletConfig);
assertNotNull(portletBean.getTestParam());
assertEquals(testValue, portletBean.getTestParam());
}
public void testRequiredInitParameterNotSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty(testParam);
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
}
public void testRequiredInitParameterNotSetOtherParameterNotSet() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty("anotherParam");
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
assertNull(portletBean.getTestParam());
}
public void testUnknownRequiredInitParameter() throws Exception {
PortletContext portletContext = new MockPortletContext();
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
String testParam = "testParam";
String testValue = "testValue";
portletConfig.addInitParameter(testParam, testValue);
TestPortletBean portletBean = new TestPortletBean();
portletBean.addRequiredProperty("unknownParam");
assertNull(portletBean.getTestParam());
try {
portletBean.init(portletConfig);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
assertNull(portletBean.getTestParam());
}
private static class TestPortletBean extends GenericPortletBean {
private String testParam;
private String anotherParam;
public void setTestParam(String value) {
this.testParam = value;
}
public String getTestParam() {
return this.testParam;
}
public void setAnotherParam(String value) {
this.anotherParam = value;
}
public String getAnotherParam() {
return this.anotherParam;
}
}
}

View File

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

View File

@@ -1,237 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind;
import java.beans.PropertyEditorSupport;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Set;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringArrayPropertyEditor;
import org.springframework.core.CollectionFactory;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.validation.BindingResult;
/**
* @author Mark Fisher
*/
public class PortletRequestDataBinderTests extends TestCase {
public void testSimpleBind() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "35");
request.addParameter("name", "test");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertEquals(35, bean.getAge());
assertEquals("test", bean.getName());
}
public void testNestedBind() {
TestBean bean = new TestBean();
bean.setSpouse(new TestBean());
MockPortletRequest request = new MockPortletRequest();
request.addParameter("spouse.name", "test");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSpouse());
assertEquals("test", bean.getSpouse().getName());
}
public void testNestedBindWithPropertyEditor() {
TestBean bean = new TestBean();
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean(text));
}
});
MockPortletRequest request = new MockPortletRequest();
request.addParameter("spouse", "test");
request.addParameter("spouse.age", "32");
binder.bind(request);
assertNotNull(bean.getSpouse());
assertEquals("test", bean.getSpouse().getName());
assertEquals(32, bean.getSpouse().getAge());
}
public void testBindingMismatch() {
TestBean bean = new TestBean();
bean.setAge(30);
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "zzz");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
BindingResult error = binder.getBindingResult();
assertNotNull(error.getFieldError("age"));
assertEquals("typeMismatch", error.getFieldError("age").getCode());
assertEquals(30, bean.getAge());
}
public void testBindingStringWithCommaSeparatedValue() throws Exception {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("stringArray", "test1,test2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getStringArray());
assertEquals(1, bean.getStringArray().length);
assertEquals("test1,test2", bean.getStringArray()[0]);
}
public void testBindingStringArrayWithSplitting() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("stringArray", "test1,test2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.registerCustomEditor(String[].class, new StringArrayPropertyEditor());
binder.bind(request);
assertNotNull(bean.getStringArray());
assertEquals(2, bean.getStringArray().length);
assertEquals("test1", bean.getStringArray()[0]);
assertEquals("test2", bean.getStringArray()[1]);
}
public void testBindingList() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someList[0]", "test1");
request.addParameter("someList[1]", "test2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSomeList());
assertEquals(2, bean.getSomeList().size());
assertEquals("test1", bean.getSomeList().get(0));
assertEquals("test2", bean.getSomeList().get(1));
}
public void testBindingMap() {
TestBean bean = new TestBean();
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someMap['key1']", "val1");
request.addParameter("someMap['key2']", "val2");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSomeMap());
assertEquals(2, bean.getSomeMap().size());
assertEquals("val1", bean.getSomeMap().get("key1"));
assertEquals("val2", bean.getSomeMap().get("key2"));
}
public void testBindingSet() {
TestBean bean = new TestBean();
Set set = CollectionFactory.createLinkedSetIfPossible(2);
set.add(new TestBean("test1"));
set.add(new TestBean("test2"));
bean.setSomeSet(set);
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someSet[0].age", "35");
request.addParameter("someSet[1].age", "36");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
assertNotNull(bean.getSomeSet());
assertEquals(2, bean.getSomeSet().size());
Iterator iter = bean.getSomeSet().iterator();
TestBean bean1 = (TestBean) iter.next();
assertEquals("test1", bean1.getName());
assertEquals(35, bean1.getAge());
TestBean bean2 = (TestBean) iter.next();
assertEquals("test2", bean2.getName());
assertEquals(36, bean2.getAge());
}
public void testBindingDate() throws Exception {
TestBean bean = new TestBean();
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date expected = dateFormat.parse("06-03-2006");
MockPortletRequest request = new MockPortletRequest();
request.addParameter("date", "06-03-2006");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
binder.bind(request);
assertEquals(expected, bean.getDate());
}
public void testBindingFailsWhenMissingRequiredParam() {
TestBean bean = new TestBean();
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.setRequiredFields(new String[] {"age", "name"});
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "35");
binder.bind(request);
BindingResult error = binder.getBindingResult();
assertNotNull(error.getFieldError("name"));
assertEquals("required", error.getFieldError("name").getCode());
}
public void testBindingExcludesDisallowedParam() {
TestBean bean = new TestBean();
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.setAllowedFields(new String[] {"age"});
MockPortletRequest request = new MockPortletRequest();
request.addParameter("age", "35");
request.addParameter("name", "test");
binder.bind(request);
assertEquals(35, bean.getAge());
assertNull(bean.getName());
}
}

View File

@@ -1,64 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind;
import org.springframework.mock.web.portlet.MockPortletRequest;
import junit.framework.TestCase;
/**
* @author Mark Fisher
*/
public class PortletRequestParameterPropertyValuesTests extends TestCase {
public void testWithNoParams() {
MockPortletRequest request = new MockPortletRequest();
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request);
assertTrue("Should not have any property values", pvs.getPropertyValues().length == 0);
}
public void testWithNoPrefix() {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param", "value");
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request);
assertEquals("value", pvs.getPropertyValue("param").getValue());
}
public void testWithPrefix() {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("test_param", "value");
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test");
assertTrue(pvs.contains("param"));
assertFalse(pvs.contains("test_param"));
assertEquals("value", pvs.getPropertyValue("param").getValue());
}
public void testWithPrefixAndOverridingSeparator() {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("test.param", "value");
request.addParameter("test_another", "anotherValue");
request.addParameter("some.other", "someValue");
PortletRequestParameterPropertyValues pvs = new PortletRequestParameterPropertyValues(request, "test", ".");
assertFalse(pvs.contains("test.param"));
assertFalse(pvs.contains("test_another"));
assertFalse(pvs.contains("some.other"));
assertFalse(pvs.contains("another"));
assertFalse(pvs.contains("other"));
assertTrue(pvs.contains("param"));
assertEquals("value", pvs.getPropertyValue("param").getValue());
}
}

View File

@@ -1,437 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.bind;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.util.StopWatch;
/**
* @author Juergen Hoeller
* @author Mark Fisher
*/
public class PortletRequestUtilsTests extends TestCase {
public void testIntParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertEquals(PortletRequestUtils.getIntParameter(request, "param1"), new Integer(5));
assertEquals(PortletRequestUtils.getIntParameter(request, "param1", 6), 5);
assertEquals(PortletRequestUtils.getRequiredIntParameter(request, "param1"), 5);
assertEquals(PortletRequestUtils.getIntParameter(request, "param2", 6), 6);
try {
PortletRequestUtils.getRequiredIntParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertEquals(PortletRequestUtils.getIntParameter(request, "param3"), null);
assertEquals(PortletRequestUtils.getIntParameter(request, "param3", 6), 6);
try {
PortletRequestUtils.getRequiredIntParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredIntParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testIntParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param", new String[] {"1", "2", "3"});
request.addParameter("param2", "1");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
int[] array = new int[] { 1, 2, 3 };
int[] values = PortletRequestUtils.getRequiredIntParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
try {
PortletRequestUtils.getRequiredIntParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testLongParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertEquals(PortletRequestUtils.getLongParameter(request, "param1"), new Long(5L));
assertEquals(PortletRequestUtils.getLongParameter(request, "param1", 6L), 5L);
assertEquals(PortletRequestUtils.getRequiredIntParameter(request, "param1"), 5L);
assertEquals(PortletRequestUtils.getLongParameter(request, "param2", 6L), 6L);
try {
PortletRequestUtils.getRequiredLongParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertEquals(PortletRequestUtils.getLongParameter(request, "param3"), null);
assertEquals(PortletRequestUtils.getLongParameter(request, "param3", 6L), 6L);
try {
PortletRequestUtils.getRequiredLongParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredLongParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testLongParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.setParameter("param", new String[] {"1", "2", "3"});
request.setParameter("param2", "0");
request.setParameter("param2", "1");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
long[] array = new long[] { 1L, 2L, 3L };
long[] values = PortletRequestUtils.getRequiredLongParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
try {
PortletRequestUtils.getRequiredLongParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
request.setParameter("param2", new String[] {"1", "2"});
values = PortletRequestUtils.getRequiredLongParameters(request, "param2");
assertEquals(2, values.length);
assertEquals(1, values[0]);
assertEquals(2, values[1]);
}
public void testFloatParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5.5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertTrue(PortletRequestUtils.getFloatParameter(request, "param1").equals(new Float(5.5f)));
assertTrue(PortletRequestUtils.getFloatParameter(request, "param1", 6.5f) == 5.5f);
assertTrue(PortletRequestUtils.getRequiredFloatParameter(request, "param1") == 5.5f);
assertTrue(PortletRequestUtils.getFloatParameter(request, "param2", 6.5f) == 6.5f);
try {
PortletRequestUtils.getRequiredFloatParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertTrue(PortletRequestUtils.getFloatParameter(request, "param3") == null);
assertTrue(PortletRequestUtils.getFloatParameter(request, "param3", 6.5f) == 6.5f);
try {
PortletRequestUtils.getRequiredFloatParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredFloatParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testFloatParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param", new String[] {"1.5", "2.5", "3"});
request.addParameter("param2", "1.5");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
float[] array = new float[] { 1.5F, 2.5F, 3 };
float[] values = PortletRequestUtils.getRequiredFloatParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i], 0);
}
try {
PortletRequestUtils.getRequiredFloatParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testDoubleParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "5.5");
request.addParameter("param2", "e");
request.addParameter("paramEmpty", "");
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param1").equals(new Double(5.5)));
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param1", 6.5) == 5.5);
assertTrue(PortletRequestUtils.getRequiredDoubleParameter(request, "param1") == 5.5);
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param2", 6.5) == 6.5);
try {
PortletRequestUtils.getRequiredDoubleParameter(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param3") == null);
assertTrue(PortletRequestUtils.getDoubleParameter(request, "param3", 6.5) == 6.5);
try {
PortletRequestUtils.getRequiredDoubleParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
try {
PortletRequestUtils.getRequiredDoubleParameter(request, "paramEmpty");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testDoubleParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param", new String[] {"1.5", "2.5", "3"});
request.addParameter("param2", "1.5");
request.addParameter("param2", "2");
request.addParameter("param2", "bogus");
double[] array = new double[] { 1.5, 2.5, 3 };
double[] values = PortletRequestUtils.getRequiredDoubleParameters(request, "param");
assertEquals(3, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i], 0);
}
try {
PortletRequestUtils.getRequiredDoubleParameters(request, "param2");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
}
public void testBooleanParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "true");
request.addParameter("param2", "e");
request.addParameter("param4", "yes");
request.addParameter("param5", "1");
request.addParameter("paramEmpty", "");
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param1").equals(Boolean.TRUE));
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param1", false));
assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param1"));
assertFalse(PortletRequestUtils.getBooleanParameter(request, "param2", true));
assertFalse(PortletRequestUtils.getRequiredBooleanParameter(request, "param2"));
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param3") == null);
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param3", true));
try {
PortletRequestUtils.getRequiredBooleanParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param4", false));
assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param4"));
assertTrue(PortletRequestUtils.getBooleanParameter(request, "param5", false));
assertTrue(PortletRequestUtils.getRequiredBooleanParameter(request, "param5"));
assertFalse(PortletRequestUtils.getRequiredBooleanParameter(request, "paramEmpty"));
}
public void testBooleanParameters() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param", new String[] {"true", "yes", "off", "1", "bogus"});
request.addParameter("param2", "false");
request.addParameter("param2", "true");
request.addParameter("param2", "");
boolean[] array = new boolean[] { true, true, false, true, false };
boolean[] values = PortletRequestUtils.getRequiredBooleanParameters(request, "param");
assertEquals(5, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
array = new boolean[] { false, true, false };
values = PortletRequestUtils.getRequiredBooleanParameters(request, "param2");
assertEquals(array.length, values.length);
for (int i = 0; i < array.length; i++) {
assertEquals(array[i], values[i]);
}
}
public void testStringParameter() throws PortletRequestBindingException {
MockPortletRequest request = new MockPortletRequest();
request.addParameter("param1", "str");
request.addParameter("paramEmpty", "");
assertEquals("str", PortletRequestUtils.getStringParameter(request, "param1"));
assertEquals("str", PortletRequestUtils.getStringParameter(request, "param1", "string"));
assertEquals("str", PortletRequestUtils.getRequiredStringParameter(request, "param1"));
assertEquals(null, PortletRequestUtils.getStringParameter(request, "param3"));
assertEquals("string", PortletRequestUtils.getStringParameter(request, "param3", "string"));
try {
PortletRequestUtils.getRequiredStringParameter(request, "param3");
fail("Should have thrown PortletRequestBindingException");
}
catch (PortletRequestBindingException ex) {
// expected
}
assertEquals("", PortletRequestUtils.getStringParameter(request, "paramEmpty"));
assertEquals("", PortletRequestUtils.getRequiredStringParameter(request, "paramEmpty"));
}
public void testGetIntParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getIntParameter(request, "nonExistingParam", 0);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetLongParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getLongParameter(request, "nonExistingParam", 0);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetFloatParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getFloatParameter(request, "nonExistingParam", 0f);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetDoubleParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getDoubleParameter(request, "nonExistingParam", 0d);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetBooleanParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getBooleanParameter(request, "nonExistingParam", false);
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
public void testGetStringParameterWithDefaultValueHandlingIsFastEnough() {
MockPortletRequest request = new MockPortletRequest();
StopWatch sw = new StopWatch();
sw.start();
for (int i = 0; i < 1000000; i++) {
PortletRequestUtils.getStringParameter(request, "nonExistingParam", "defaultValue");
}
sw.stop();
System.out.println(sw.getTotalTimeMillis());
assertTrue("getStringParameter took too long: " + sw.getTotalTimeMillis(), sw.getTotalTimeMillis() < 250);
}
}

View File

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

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.context;
import javax.portlet.PortletConfig;
/**
* @author Mark Fisher
*/
public class PortletConfigAwareBean implements PortletConfigAware {
private PortletConfig portletConfig;
public void setPortletConfig(PortletConfig portletConfig) {
this.portletConfig = portletConfig;
}
public PortletConfig getPortletConfig() {
return portletConfig;
}
}

View File

@@ -1,35 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.context;
import javax.portlet.PortletContext;
/**
* @author Mark Fisher
*/
public class PortletContextAwareBean implements PortletContextAware {
private PortletContext portletContext;
public void setPortletContext(PortletContext portletContext) {
this.portletContext = portletContext;
}
public PortletContext getPortletContext() {
return portletContext;
}
}

View File

@@ -1,154 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.context;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
/**
* @author Mark Fisher
*/
public class PortletContextAwareProcessorTests extends TestCase {
public void testPortletContextAwareWithPortletContext() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithPortletContextAndPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithNullPortletContextAndNonNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithNonNullPortletContextAndNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletContext should have been set", bean.getPortletContext());
assertEquals(portletContext, bean.getPortletContext());
}
public void testPortletContextAwareWithNullPortletContext() {
PortletContext portletContext = null;
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletContextAwareBean bean = new PortletContextAwareBean();
assertNull(bean.getPortletContext());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletContext());
}
public void testPortletConfigAwareWithPortletContextOnly() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletConfig());
}
public void testPortletConfigAwareWithPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletConfig);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletConfig should have been set", bean.getPortletConfig());
assertEquals(portletConfig, bean.getPortletConfig());
}
public void testPortletConfigAwareWithPortletContextAndPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, portletConfig);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletConfig should have been set", bean.getPortletConfig());
assertEquals(portletConfig, bean.getPortletConfig());
}
public void testPortletConfigAwareWithNullPortletContextAndNonNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(null, portletConfig);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNotNull("PortletConfig should have been set", bean.getPortletConfig());
assertEquals(portletConfig, bean.getPortletConfig());
}
public void testPortletConfigAwareWithNonNullPortletContextAndNullPortletConfig() {
PortletContext portletContext = new MockPortletContext();
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext, null);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletConfig());
}
public void testPortletConfigAwareWithNullPortletContext() {
PortletContext portletContext = null;
PortletContextAwareProcessor processor = new PortletContextAwareProcessor(portletContext);
PortletConfigAwareBean bean = new PortletConfigAwareBean();
assertNull(bean.getPortletConfig());
processor.postProcessBeforeInitialization(bean, "testBean");
assertNull(bean.getPortletConfig());
}
}

View File

@@ -1,170 +0,0 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.context;
import java.io.Serializable;
import javax.portlet.PortletRequest;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.mock.web.portlet.MockPortletSession;
import org.springframework.test.AssertThrows;
import org.springframework.web.context.request.RequestAttributes;
/**
* @author Rick Evans
* @author Juergen Hoeller
*/
public class PortletRequestAttributesTests extends TestCase {
private static final String KEY = "ThatThingThatThing";
private static final Serializable VALUE = new Serializable() {
};
public void testCtorRejectsNullArg() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
new PortletRequestAttributes(null);
}
}.runTest();
}
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();
}
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);
}
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
}
}
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);
}
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);
}
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);
}
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);
}
public void testGetSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(false);
mockRequest.setReturnValue(null, 1);
mockRequest.replay();
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
Object value = attrs.getAttribute(KEY, RequestAttributes.SCOPE_SESSION);
assertNull(value);
mockRequest.verify();
}
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);
}
public void testRemoveSessionScopedAttributeDoesNotForceCreationOfSession() throws Exception {
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(false);
mockRequest.setReturnValue(null, 1);
mockRequest.replay();
PortletRequestAttributes attrs = new PortletRequestAttributes(request);
attrs.removeAttribute(KEY, RequestAttributes.SCOPE_SESSION);
mockRequest.verify();
}
}

View File

@@ -1,64 +0,0 @@
/*
* 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());
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,134 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.context;
import java.util.Locale;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.NoSuchMessageException;
import org.springframework.mock.web.portlet.MockPortletConfig;
import org.springframework.mock.web.portlet.MockPortletContext;
/**
* @author Rod Johnson
* @author Juergen Hoeller
* @author Mark Fisher
* @author Chris Beams
*/
public class XmlPortletApplicationContextTests extends AbstractXmlWebApplicationContextTests {
private ConfigurablePortletApplicationContext root;
protected ConfigurableApplicationContext createContext() throws Exception {
root = new XmlPortletApplicationContext();
PortletContext portletContext = new MockPortletContext();
PortletConfig portletConfig = new MockPortletConfig(portletContext);
root.setPortletConfig(portletConfig);
root.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/applicationContext.xml"});
root.addBeanFactoryPostProcessor(new BeanFactoryPostProcessor() {
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
beanFactory.addBeanPostProcessor(new BeanPostProcessor() {
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof TestBean) {
((TestBean) bean).getFriends().add("myFriend");
}
return bean;
}
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
return bean;
}
});
}
});
root.refresh();
XmlPortletApplicationContext pac = new XmlPortletApplicationContext();
pac.setParent(root);
pac.setPortletConfig(portletConfig);
pac.setNamespace("test-portlet");
pac.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml"});
pac.refresh();
return pac;
}
/**
* Overridden in order to use MockPortletConfig
* @see org.springframework.web.context.XmlWebApplicationContextTests#testWithoutMessageSource()
*/
public void testWithoutMessageSource() throws Exception {
MockPortletContext portletContext = new MockPortletContext("");
MockPortletConfig portletConfig = new MockPortletConfig(portletContext);
XmlPortletApplicationContext pac = new XmlPortletApplicationContext();
pac.setParent(root);
pac.setPortletConfig(portletConfig);
pac.setNamespace("testNamespace");
pac.setConfigLocations(new String[] {"/org/springframework/web/portlet/context/WEB-INF/test-portlet.xml"});
pac.refresh();
try {
pac.getMessage("someMessage", null, Locale.getDefault());
fail("Should have thrown NoSuchMessageException");
}
catch (NoSuchMessageException ex) {
// expected;
}
String msg = pac.getMessage("someMessage", null, "default", Locale.getDefault());
assertTrue("Default message returned", "default".equals(msg));
}
/**
* Overridden in order to access the root ApplicationContext
* @see org.springframework.web.context.XmlWebApplicationContextTests#testContextNesting()
*/
public void testContextNesting() {
TestBean father = (TestBean) this.applicationContext.getBean("father");
assertTrue("Bean from root context", father != null);
assertTrue("Custom BeanPostProcessor applied", father.getFriends().contains("myFriend"));
TestBean rod = (TestBean) this.applicationContext.getBean("rod");
assertTrue("Bean from child context", "Rod".equals(rod.getName()));
assertTrue("Bean has external reference", rod.getSpouse() == father);
assertTrue("Custom BeanPostProcessor not applied", !rod.getFriends().contains("myFriend"));
rod = (TestBean) this.root.getBean("rod");
assertTrue("Bean from root context", "Roderick".equals(rod.getName()));
assertTrue("Custom BeanPostProcessor applied", rod.getFriends().contains("myFriend"));
}
public void testCount() {
assertTrue("should have 16 beans, not "+ this.applicationContext.getBeanDefinitionCount(),
this.applicationContext.getBeanDefinitionCount() == 16);
}
public void testPortletContextAwareBean() {
PortletContextAwareBean bean = (PortletContextAwareBean)this.applicationContext.getBean("portletContextAwareBean");
assertNotNull(bean.getPortletContext());
}
public void testPortletConfigAwareBean() {
PortletConfigAwareBean bean = (PortletConfigAwareBean)this.applicationContext.getBean("portletConfigAwareBean");
assertNotNull(bean.getPortletConfig());
}
}

View File

@@ -1,103 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.web.portlet.HandlerMapping;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class ParameterHandlerMappingTests extends TestCase {
public static final String CONF = "/org/springframework/web/portlet/handler/parameterMapping.xml";
private ConfigurablePortletApplicationContext pac;
public void setUp() throws Exception {
MockPortletContext portletContext = new MockPortletContext();
pac = new XmlPortletApplicationContext();
pac.setPortletContext(portletContext);
pac.setConfigLocations(new String[] {CONF});
pac.refresh();
}
public void testParameterMapping() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest addRequest = new MockPortletRequest();
addRequest.addParameter("action", "add");
MockPortletRequest removeRequest = new MockPortletRequest();
removeRequest.addParameter("action", "remove");
Object addHandler = hm.getHandler(addRequest).getHandler();
Object removeHandler = hm.getHandler(removeRequest).getHandler();
assertEquals(pac.getBean("addItemHandler"), addHandler);
assertEquals(pac.getBean("removeItemHandler"), removeHandler);
}
public void testUnregisteredHandlerWithNoDefault() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.addParameter("action", "modify");
assertNull(hm.getHandler(request));
}
public void testUnregisteredHandlerWithDefault() throws Exception {
ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping");
Object defaultHandler = new Object();
hm.setDefaultHandler(defaultHandler);
MockPortletRequest request = new MockPortletRequest();
request.addParameter("action", "modify");
assertNotNull(hm.getHandler(request));
assertEquals(defaultHandler, hm.getHandler(request).getHandler());
}
public void testConfiguredParameterName() throws Exception {
ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping");
hm.setParameterName("someParam");
MockPortletRequest request = new MockPortletRequest();
request.addParameter("someParam", "add");
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("addItemHandler"), handler);
}
public void testDuplicateMappingAttempt() {
ParameterHandlerMapping hm = (ParameterHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler("add", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
}

View File

@@ -1,131 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
/**
* @author Mark Fisher
*/
public class ParameterMappingInterceptorTests extends TestCase {
public void testDefaultParameterMapped() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME;
String value = "someValue";
request.setParameter(param, value);
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandleAction(request, response, handler);
assertTrue(shouldProceed);
assertNotNull(response.getRenderParameter(param));
assertEquals(value, response.getRenderParameter(param));
}
public void testNonDefaultParameterNotMapped() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = "myParam";
String value = "someValue";
request.setParameter(param, value);
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME));
}
public void testNonDefaultParameterMappedWhenHandlerMappingProvided() throws Exception {
String param = "myParam";
String value = "someValue";
ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping();
handlerMapping.setParameterName(param);
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
interceptor.setParameterName(param);
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
request.setParameter(param, value);
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandleAction(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(ParameterHandlerMapping.DEFAULT_PARAMETER_NAME));
assertNotNull(response.getRenderParameter(param));
assertEquals(value, response.getRenderParameter(param));
}
public void testNoEffectForRenderRequest() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME;
String value = "someValue";
request.setParameter(param, value);
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
}
public void testNoParameterValueSetWithDefaultParameterName() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = ParameterHandlerMapping.DEFAULT_PARAMETER_NAME;
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
}
public void testNoParameterValueSetWithNonDefaultParameterName() throws Exception {
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
String param = "myParam";
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
}
public void testNoParameterValueSetWithNonDefaultParameterNameWhenHandlerMappingProvided() throws Exception {
String param = "myParam";
ParameterHandlerMapping handlerMapping = new ParameterHandlerMapping();
handlerMapping.setParameterName(param);
ParameterMappingInterceptor interceptor = new ParameterMappingInterceptor();
interceptor.setParameterName(param);
Object handler = new Object();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
assertNull(response.getRenderParameter(param));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
assertNull(response.getRenderParameter(param));
}
}

View File

@@ -1,87 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import javax.portlet.PortletMode;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.web.portlet.HandlerMapping;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class PortletModeHandlerMappingTests extends TestCase {
public static final String CONF = "/org/springframework/web/portlet/handler/portletModeMapping.xml";
private ConfigurablePortletApplicationContext pac;
public void setUp() throws Exception {
MockPortletContext portletContext = new MockPortletContext();
pac = new XmlPortletApplicationContext();
pac.setPortletContext(portletContext);
pac.setConfigLocations(new String[] {CONF});
pac.refresh();
}
public void testPortletModeView() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.VIEW);
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("viewHandler"), handler);
}
public void testPortletModeEdit() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.EDIT);
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("editHandler"), handler);
}
public void testPortletModeHelp() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.HELP);
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("helpHandler"), handler);
}
public void testDuplicateMappingAttempt() {
PortletModeHandlerMapping hm = (PortletModeHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler(PortletMode.VIEW, new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import javax.portlet.PortletMode;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockPortletContext;
import org.springframework.mock.web.portlet.MockPortletRequest;
import org.springframework.web.portlet.HandlerMapping;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.XmlPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class PortletModeParameterHandlerMappingTests extends TestCase {
public static final String CONF = "/org/springframework/web/portlet/handler/portletModeParameterMapping.xml";
private ConfigurablePortletApplicationContext pac;
public void setUp() throws Exception {
MockPortletContext portletContext = new MockPortletContext();
pac = new XmlPortletApplicationContext();
pac.setPortletContext(portletContext);
pac.setConfigLocations(new String[] {CONF});
pac.refresh();
}
public void testPortletModeViewWithParameter() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest addRequest = new MockPortletRequest();
addRequest.setPortletMode(PortletMode.VIEW);
addRequest.setParameter("action", "add");
MockPortletRequest removeRequest = new MockPortletRequest();
removeRequest.setPortletMode(PortletMode.VIEW);
removeRequest.setParameter("action", "remove");
Object addHandler = hm.getHandler(addRequest).getHandler();
Object removeHandler = hm.getHandler(removeRequest).getHandler();
assertEquals(pac.getBean("addItemHandler"), addHandler);
assertEquals(pac.getBean("removeItemHandler"), removeHandler);
}
public void testPortletModeEditWithParameter() throws Exception {
HandlerMapping hm = (HandlerMapping)pac.getBean("handlerMapping");
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.EDIT);
request.setParameter("action", "prefs");
Object handler = hm.getHandler(request).getHandler();
assertEquals(pac.getBean("preferencesHandler"), handler);
}
public void testDuplicateMappingInSamePortletMode() {
PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler(PortletMode.VIEW, "remove", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
public void testDuplicateMappingInDifferentPortletMode() {
PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping");
try {
hm.registerHandler(PortletMode.EDIT, "remove", new Object());
fail("Should have thrown IllegalStateException");
}
catch (IllegalStateException ex) {
// expected
}
}
public void testAllowDuplicateMappingInDifferentPortletMode() throws Exception {
PortletModeParameterHandlerMapping hm = (PortletModeParameterHandlerMapping)pac.getBean("handlerMapping");
hm.setAllowDuplicateParameters(true);
Object editRemoveHandler = new Object();
hm.registerHandler(PortletMode.EDIT, "remove", editRemoveHandler);
MockPortletRequest request = new MockPortletRequest();
request.setPortletMode(PortletMode.EDIT);
request.setParameter("action", "remove");
Object handler = hm.getHandler(request).getHandler();
assertEquals(editRemoveHandler, handler);
}
}

View File

@@ -1,277 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import java.util.Collections;
import java.util.Properties;
import javax.portlet.WindowState;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* @author Seth Ladd
* @author Mark Fisher
* @author Juergen Hoeller
*/
public class SimpleMappingExceptionResolverTests extends TestCase {
private static final String DEFAULT_VIEW = "default-view";
private SimpleMappingExceptionResolver exceptionResolver;
private MockRenderRequest request;
private MockRenderResponse response;
private Object handler1;
private Object handler2;
private Exception genericException;
protected void setUp() {
exceptionResolver = new SimpleMappingExceptionResolver();
request = new MockRenderRequest();
response = new MockRenderResponse();
handler1 = new String();
handler2 = new Object();
genericException = new Exception();
}
public void testSetOrder() {
exceptionResolver.setOrder(2);
assertEquals(2, exceptionResolver.getOrder());
}
public void testDefaultErrorView() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals(DEFAULT_VIEW, mav.getViewName());
assertEquals(genericException, mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE));
}
public void testDefaultErrorViewDifferentHandler() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testDefaultErrorViewDifferentHandlerClass() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setMappedHandlerClasses(new Class[] {String.class});
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testNullDefaultErrorView() {
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNull("No default error view set - ModelAndView should be null", mav);
}
public void testNullExceptionAttribute() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setExceptionAttribute(null);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals(DEFAULT_VIEW, mav.getViewName());
assertNull(mav.getModel().get(SimpleMappingExceptionResolver.DEFAULT_EXCEPTION_ATTRIBUTE));
}
public void testNullExceptionMappings() {
exceptionResolver.setExceptionMappings(null);
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals(DEFAULT_VIEW, mav.getViewName());
}
public void testDefaultNoRenderWhenMinimized() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
request.setWindowState(WindowState.MINIMIZED);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNull("Should not render when WindowState is MINIMIZED", mav);
}
public void testDoRenderWhenMinimized() {
exceptionResolver.setDefaultErrorView(DEFAULT_VIEW);
exceptionResolver.setRenderWhenMinimized(true);
request.setWindowState(WindowState.MINIMIZED);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNotNull("ModelAndView should not be null", mav);
assertEquals(DEFAULT_VIEW, mav.getViewName());
}
public void testSimpleExceptionMapping() {
Properties props = new Properties();
props.setProperty("Exception", "error");
exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION");
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testExactExceptionMappingWithHandlerSpecified() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testExactExceptionMappingWithHandlerClassSpecified() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
exceptionResolver.setMappedHandlerClasses(new Class[] {String.class});
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testExactExceptionMappingWithHandlerInterfaceSpecified() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
exceptionResolver.setMappedHandlerClasses(new Class[] {Comparable.class});
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testSimpleExceptionMappingWithHandlerSpecifiedButWrongHandler() {
Properties props = new Properties();
props.setProperty("Exception", "error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testSimpleExceptionMappingWithHandlerSpecifiedButWrongHandlerClass() {
Properties props = new Properties();
props.setProperty("Exception", "error");
exceptionResolver.setMappedHandlerClasses(new Class[] {String.class});
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler2, genericException);
assertNull("Handler not mapped - ModelAndView should be null", mav);
}
public void testMissingExceptionInMapping() {
Properties props = new Properties();
props.setProperty("SomeFooThrowable", "error");
exceptionResolver.setWarnLogCategory("HANDLER_EXCEPTION");
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertNull("Exception not mapped - ModelAndView should be null", mav);
}
public void testTwoMappings() {
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("AnotherException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testTwoMappingsOneShortOneLong() {
Properties props = new Properties();
props.setProperty("Exception", "error");
props.setProperty("AnotherException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, genericException);
assertEquals("error", mav.getViewName());
}
public void testTwoMappingsOneShortOneLongThrowOddException() {
Exception oddException = new SomeOddException();
Properties props = new Properties();
props.setProperty("Exception", "error");
props.setProperty("SomeOddException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("error", mav.getViewName());
}
public void testTwoMappingsThrowOddExceptionUseLongExceptionMapping() {
Exception oddException = new SomeOddException();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "another-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("another-error", mav.getViewName());
}
public void testThreeMappings() {
Exception oddException = new AnotherOddException();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "another-error");
props.setProperty("AnotherOddException", "another-some-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("another-some-error", mav.getViewName());
}
public void testExceptionWithSubstringMatchingParent() {
Exception oddException = new SomeOddExceptionChild();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "parent-error");
props.setProperty("SomeOddExceptionChild", "child-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("child-error", mav.getViewName());
}
public void testMostSpecificExceptionInHierarchyWins() {
Exception oddException = new NoSubstringMatchesThisException();
Properties props = new Properties();
props.setProperty("java.lang.Exception", "error");
props.setProperty("SomeOddException", "parent-error");
exceptionResolver.setMappedHandlers(Collections.singleton(handler1));
exceptionResolver.setExceptionMappings(props);
ModelAndView mav = exceptionResolver.resolveException(request, response, handler1, oddException);
assertEquals("parent-error", mav.getViewName());
}
private static class SomeOddException extends Exception {
}
private static class SomeOddExceptionChild extends SomeOddException {
}
private static class NoSubstringMatchesThisException extends SomeOddException {
}
private static class AnotherOddException extends Exception {
}
}

View File

@@ -1,110 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.handler;
import javax.portlet.PortletSecurityException;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
/**
* @author Mark Fisher
*/
public class UserRoleAuthorizationInterceptorTests extends TestCase {
public void testAuthorizedUser() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole = "allowed";
interceptor.setAuthorizedRoles(new String[] {validRole});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole(validRole);
assertTrue(request.isUserInRole(validRole));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
}
public void testAuthorizedUserWithMultipleRoles() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole1 = "allowed1";
String validRole2 = "allowed2";
interceptor.setAuthorizedRoles(new String[] {validRole1, validRole2});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole(validRole2);
request.addUserRole("someOtherRole");
assertFalse(request.isUserInRole(validRole1));
assertTrue(request.isUserInRole(validRole2));
boolean shouldProceed = interceptor.preHandle(request, response, handler);
assertTrue(shouldProceed);
}
public void testUnauthorizedUser() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole = "allowed";
interceptor.setAuthorizedRoles(new String[] {validRole});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole("someOtherRole");
assertFalse(request.isUserInRole(validRole));
try {
interceptor.preHandle(request, response, handler);
fail("should have thrown PortletSecurityException");
}
catch (PortletSecurityException ex) {
// expected
}
}
public void testRequestWithNoUserRoles() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
String validRole = "allowed";
interceptor.setAuthorizedRoles(new String[] {validRole});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
assertFalse(request.isUserInRole(validRole));
try {
interceptor.preHandle(request, response, handler);
fail("should have thrown PortletSecurityException");
}
catch (PortletSecurityException ex) {
// expected
}
}
public void testInterceptorWithNoAuthorizedRoles() throws Exception {
UserRoleAuthorizationInterceptor interceptor = new UserRoleAuthorizationInterceptor();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
Object handler = new Object();
request.addUserRole("someRole");
try {
interceptor.preHandle(request, response, handler);
fail("should have thrown PortletSecurityException");
}
catch (PortletSecurityException ex) {
// expected
}
}
}

View File

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

View File

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

View File

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

View File

@@ -1,461 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.mvc;
import java.beans.PropertyEditorSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletRequest;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.WindowState;
import junit.framework.TestCase;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.bind.PortletRequestDataBinder;
import org.springframework.web.portlet.handler.PortletSessionRequiredException;
/**
* @author Mark Fisher
*/
public class CommandControllerTests extends TestCase {
private static final String ERRORS_KEY = "errors";
public void testRenderRequestWithNoParams() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
assertNotNull(mav.getModel().get(tc.getCommandName()));
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertNotNull(errors);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testRenderRequestWithParams() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals("Name should be bound", name, command.getName());
assertEquals("Age should be bound", age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertNotNull(errors);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testRenderRequestWithMismatch() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
request.addParameter("name", name);
request.addParameter("age", "zzz");
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertNotNull(command);
assertEquals("Name should be bound", name, command.getName());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
assertNotNull(errors.getFieldError("age"));
assertEquals("typeMismatch", errors.getFieldError("age").getCode());
}
public void testRenderWhenMinimizedReturnsNull() throws Exception {
TestController tc = new TestController();
assertFalse(tc.isRenderWhenMinimized());
MockRenderRequest request = new MockRenderRequest();
request.setWindowState(WindowState.MINIMIZED);
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
assertNull("ModelAndView should be null", mav);
}
public void testAllowRenderWhenMinimized() throws Exception {
TestController tc = new TestController();
tc.setRenderWhenMinimized(true);
MockRenderRequest request = new MockRenderRequest();
request.setWindowState(WindowState.MINIMIZED);
request.setContextPath("test");
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
assertNotNull("ModelAndView should not be null", mav);
assertEquals("test-view", mav.getViewName());
assertNotNull(mav.getModel().get(tc.getCommandName()));
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testRequiresSessionWithoutSession() throws Exception {
TestController tc = new TestController();
tc.setRequireSession(true);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
try {
tc.handleRenderRequest(request, response);
fail("Should have thrown PortletSessionRequiredException");
}
catch (PortletSessionRequiredException ex) {
// expected
}
}
public void testRequiresSessionWithSession() throws Exception {
TestController tc = new TestController();
tc.setRequireSession(true);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
// create the session
request.getPortletSession(true);
try {
tc.handleRenderRequest(request, response);
}
catch (PortletSessionRequiredException ex) {
fail("Should not have thrown PortletSessionRequiredException");
}
}
public void testRenderRequestWithoutCacheSetting() throws Exception {
TestController tc = new TestController();
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertNull("Expiration-cache should be null", cacheProperty);
}
public void testRenderRequestWithNegativeCacheSetting() throws Exception {
TestController tc = new TestController();
tc.setCacheSeconds(-99);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertNull("Expiration-cache should be null", cacheProperty);
}
public void testRenderRequestWithZeroCacheSetting() throws Exception {
TestController tc = new TestController();
tc.setCacheSeconds(0);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertEquals("Expiration-cache should be set to 0 seconds", "0", cacheProperty);
}
public void testRenderRequestWithPositiveCacheSetting() throws Exception {
TestController tc = new TestController();
tc.setCacheSeconds(30);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
tc.handleRenderRequest(request, response);
String cacheProperty = response.getProperty(RenderResponse.EXPIRATION_CACHE);
assertEquals("Expiration-cache should be set to 30 seconds", "30", cacheProperty);
}
public void testActionRequest() throws Exception {
TestController tc = new TestController();
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
tc.handleActionRequest(request, response);
TestBean command = (TestBean)request.getPortletSession().getAttribute(tc.getRenderCommandSessionAttributeName());
assertTrue(command.isJedi());
}
public void testSuppressBinding() throws Exception {
TestController tc = new TestController() {
protected boolean suppressBinding(PortletRequest request) {
return true;
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
request.setContextPath("test");
ModelAndView mav = tc.handleRenderRequest(request, response);
assertEquals("test-view", mav.getViewName());
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertNotNull(command);
assertTrue("Name should not have been bound", name != command.getName());
assertTrue("Age should not have been bound", age != command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testWithCustomDateEditor() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
String dateString = "07-03-2006";
Date expectedDate = dateFormat.parse(dateString);
request.addParameter("date", dateString);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
assertEquals(expectedDate, command.getDate());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testWithCustomDateEditorEmptyNotAllowed() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
String emptyString = "";
request.addParameter("date", emptyString);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
assertNotNull(errors.getFieldError("date"));
assertEquals("typeMismatch", errors.getFieldError("date").getCode());
assertEquals(emptyString, errors.getFieldError("date").getRejectedValue());
}
public void testWithCustomDateEditorEmptyAllowed() throws Exception {
final DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
int age = 30;
request.addParameter("name", name);
request.addParameter("age", "" + age);
String dateString = "";
request.addParameter("date", dateString);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 0 errors", 0, errors.getErrorCount());
assertNull("date should be null", command.getDate());
}
public void testNestedBindingWithPropertyEditor() throws Exception {
TestController tc = new TestController() {
protected void initBinder(PortletRequest request, PortletRequestDataBinder binder) {
binder.registerCustomEditor(ITestBean.class, new PropertyEditorSupport() {
public void setAsText(String text) throws IllegalArgumentException {
setValue(new TestBean(text));
}
});
}
};
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
String name = "test";
String spouseName = "testSpouse";
int age = 30;
int spouseAge = 31;
request.addParameter("name", name);
request.addParameter("age", "" + age);
request.addParameter("spouse", spouseName);
request.addParameter("spouse.age", "" + spouseAge);
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertEquals(name, command.getName());
assertEquals(age, command.getAge());
assertNotNull(command.getSpouse());
assertEquals(spouseName, command.getSpouse().getName());
assertEquals(spouseAge, command.getSpouse().getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be no errors", 0, errors.getErrorCount());
}
public void testWithValidatorNotSupportingCommandClass() throws Exception {
Validator v = new Validator() {
public boolean supports(Class c) {
return false;
}
public void validate(Object o, Errors e) {}
};
TestController tc = new TestController();
tc.setValidator(v);
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
try {
tc.handleRenderRequest(request, response);
fail("Should have thrown IllegalArgumentException");
}
catch(IllegalArgumentException e) {
// expected
}
}
public void testWithValidatorAddingGlobalError() throws Exception {
final String errorCode = "someCode";
final String defaultMessage = "validation error!";
TestController tc = new TestController();
tc.setValidator(new Validator() {
public boolean supports(Class c) {
return TestBean.class.isAssignableFrom(c);
}
public void validate(Object o, Errors e) {
e.reject(errorCode, defaultMessage);
}
});
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
ObjectError error = errors.getGlobalError();
assertEquals(error.getCode(), errorCode);
assertEquals(error.getDefaultMessage(), defaultMessage);
}
public void testWithValidatorAndNullFieldError() throws Exception {
final String errorCode = "someCode";
final String defaultMessage = "validation error!";
TestController tc = new TestController();
tc.setValidator(new Validator() {
public boolean supports(Class c) {
return TestBean.class.isAssignableFrom(c);
}
public void validate(Object o, Errors e) {
ValidationUtils.rejectIfEmpty(e, "name", errorCode, defaultMessage);
}
});
MockRenderRequest request = new MockRenderRequest();
int age = 32;
request.setParameter("age", "" + age);
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertNull("name should be null", command.getName());
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
FieldError error = errors.getFieldError("name");
assertEquals(error.getCode(), errorCode);
assertEquals(error.getDefaultMessage(), defaultMessage);
}
public void testWithValidatorAndWhitespaceFieldError() throws Exception {
final String errorCode = "someCode";
final String defaultMessage = "validation error!";
TestController tc = new TestController();
tc.setValidator(new Validator() {
public boolean supports(Class c) {
return TestBean.class.isAssignableFrom(c);
}
public void validate(Object o, Errors e) {
ValidationUtils.rejectIfEmptyOrWhitespace(e, "name", errorCode, defaultMessage);
}
});
MockRenderRequest request = new MockRenderRequest();
int age = 32;
String whitespace = " \t ";
request.setParameter("age", "" + age);
request.setParameter("name", whitespace);
MockRenderResponse response = new MockRenderResponse();
ModelAndView mav = tc.handleRenderRequest(request, response);
TestBean command = (TestBean)mav.getModel().get(tc.getCommandName());
assertTrue(command.getName().equals(whitespace));
assertEquals(age, command.getAge());
BindException errors = (BindException)mav.getModel().get(ERRORS_KEY);
assertEquals("There should be 1 error", 1, errors.getErrorCount());
FieldError error = errors.getFieldError("name");
assertEquals("rejected value should contain whitespace", whitespace, error.getRejectedValue());
assertEquals(error.getCode(), errorCode);
assertEquals(error.getDefaultMessage(), defaultMessage);
}
private static class TestController extends AbstractCommandController {
private TestController() {
super(TestBean.class, "testBean");
}
protected void handleAction(ActionRequest request, ActionResponse response, Object command, BindException errors) {
((TestBean)command).setJedi(true);
}
protected ModelAndView handleRender(RenderRequest request, RenderResponse response, Object command, BindException errors) {
assertNotNull(command);
assertNotNull(errors);
Map model = new HashMap();
model.put(getCommandName(), command);
model.put(ERRORS_KEY, errors);
return new ModelAndView(request.getContextPath() + "-view", model);
}
}
}

View File

@@ -1,73 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.mvc;
import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
/**
* @author Mark Fisher
*/
public class ParameterizableViewControllerTests extends TestCase {
public void testRenderRequestWithViewNameSet() throws Exception {
ParameterizableViewController controller = new ParameterizableViewController();
String viewName = "testView";
controller.setViewName(viewName);
RenderRequest request = new MockRenderRequest();
RenderResponse response = new MockRenderResponse();
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals(viewName, mav.getViewName());
}
public void testInitApplicationContextWithNoViewNameSet() throws Exception {
ParameterizableViewController controller = new ParameterizableViewController();
try {
controller.setApplicationContext(new StaticPortletApplicationContext());
fail("should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testActionRequestNotHandled() throws Exception {
ParameterizableViewController controller = new ParameterizableViewController();
ActionRequest request = new MockActionRequest();
ActionResponse response = new MockActionResponse();
try {
controller.handleActionRequest(request, response);
fail("should have thrown PortletException");
}
catch (PortletException ex) {
// expected
}
}
}

View File

@@ -1,76 +0,0 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.portlet.mvc;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import junit.framework.TestCase;
import org.springframework.mock.web.portlet.MockActionRequest;
import org.springframework.mock.web.portlet.MockActionResponse;
import org.springframework.mock.web.portlet.MockRenderRequest;
import org.springframework.mock.web.portlet.MockRenderResponse;
import org.springframework.web.portlet.ModelAndView;
/**
* @author Mark Fisher
*/
public class PortletModeNameViewControllerTests extends TestCase {
private PortletModeNameViewController controller;
public void setUp() {
controller = new PortletModeNameViewController();
}
public void testEditPortletMode() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.EDIT);
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals("edit", mav.getViewName());
}
public void testHelpPortletMode() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.HELP);
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals("help", mav.getViewName());
}
public void testViewPortletMode() throws Exception {
MockRenderRequest request = new MockRenderRequest();
MockRenderResponse response = new MockRenderResponse();
request.setPortletMode(PortletMode.VIEW);
ModelAndView mav = controller.handleRenderRequest(request, response);
assertEquals("view", mav.getViewName());
}
public void testActionRequest() throws Exception {
MockActionRequest request = new MockActionRequest();
MockActionResponse response = new MockActionResponse();
try {
controller.handleActionRequest(request, response);
fail("Should have thrown PortletException");
}
catch(PortletException ex) {
// expected
}
}
}

View File

@@ -1,188 +0,0 @@
/*
* 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 junit.framework.TestCase;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.mock.web.portlet.*;
import org.springframework.test.AssertThrows;
import org.springframework.web.portlet.context.ConfigurablePortletApplicationContext;
import org.springframework.web.portlet.context.StaticPortletApplicationContext;
import javax.portlet.*;
import java.io.IOException;
/**
* Unit tests for the {@link PortletWrappingController} class.
*
* @author Mark Fisher
* @author Rick Evans
*/
public final class PortletWrappingControllerTests extends TestCase {
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;
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);
}
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);
}
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);
}
public void testActionRequestWithNoParameters() throws Exception {
final MockActionRequest request = new MockActionRequest();
final MockActionResponse response = new MockActionResponse();
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
controller.handleActionRequest(request, response);
}
}.runTest();
}
public void testRejectsPortletClassThatDoesNotImplementPortletInterface() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(String.class);
controller.afterPropertiesSet();
}
}.runTest();
}
public void testRejectsIfPortletClassIsNotSupplied() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletWrappingController controller = new PortletWrappingController();
controller.setPortletClass(null);
controller.afterPropertiesSet();
}
}.runTest();
}
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 :(
new AssertThrows(IllegalStateException.class) {
public void test() throws Exception {
controller.destroy();
}
}.runTest();
}
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);
}
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();
}
}
}

View File

@@ -1,777 +0,0 @@
/*
* 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"));
}
}
}

View File

@@ -1,605 +0,0 @@
/*
* 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 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 junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.ITestBean;
import org.springframework.beans.TestBean;
import org.springframework.mock.easymock.AbstractScalarMockTemplate;
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.test.AssertThrows;
import org.springframework.web.util.WebUtils;
/**
* @author Rick Evans
*/
public final class PortletUtilsTests extends TestCase {
public void testGetTempDirWithNullPortletContext() throws Exception {
new AssertThrows(IllegalArgumentException.class, "null PortletContext passed as argument") {
public void test() throws Exception {
PortletUtils.getTempDir(null);
}
}.runTest();
}
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;
new AbstractScalarMockTemplate(PortletContext.class) {
public void setupExpectations(MockControl mockControl, Object mockObject) throws Exception {
PortletContext ctx = (PortletContext) mockObject;
ctx.getRealPath(expectedRealPath);
mockControl.setReturnValue(expectedRealPath);
}
public void doTest(Object mockObject) throws Exception {
PortletContext ctx = (PortletContext) mockObject;
String actualRealPath = PortletUtils.getRealPath(ctx, originalPath);
assertEquals(expectedRealPath, actualRealPath);
}
}.test();
}
public void testGetRealPathWithNullPortletContext() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getRealPath(null, "/foo");
}
}.runTest();
}
public void testGetRealPathWithNullPath() throws Exception {
new AssertThrows(NullPointerException.class) {
public void test() throws Exception {
PortletUtils.getRealPath(new MockPortletContext(), null);
}
}.runTest();
}
public void testGetRealPathWithPathThatCannotBeResolvedToFile() throws Exception {
new AssertThrows(FileNotFoundException.class) {
public void test() throws Exception {
PortletUtils.getRealPath(new MockPortletContext() {
public String getRealPath(String path) {
return null;
}
}, "/rubbish");
}
}.runTest();
}
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());
}
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));
}
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));
}
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"));
}
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"));
}
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());
}
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);
}
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);
}
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);
}
public void testGetSubmitParameterWithNullRequest() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
final String targetSubmitParameter = "William";
MockPortletRequest request = new MockPortletRequest();
request.setParameter(targetSubmitParameter, "Baskerville");
request.setParameter("Adso", "Melk");
PortletUtils.getSubmitParameter(null, targetSubmitParameter);
}
}.runTest();
}
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());
}
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());
}
public void testClearAllRenderParametersDoesNotPropagateExceptionIfRedirectAlreadySentAtTimeOfCall() throws Exception {
MockActionResponse response = new MockActionResponse() {
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());
}
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));
}
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));
}
public void testHasSubmitParameterWithNoParameterMatch() throws Exception {
MockPortletRequest request = new MockPortletRequest();
request.setParameter("Bill", "Baskerville");
request.setParameter("Adso", "Melk");
assertFalse(PortletUtils.hasSubmitParameter(request, "William"));
}
public void testHasSubmitParameterWithNullRequest() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.hasSubmitParameter(null, "bingo");
}
}.runTest();
}
public void testExposeRequestAttributesWithNullRequest() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.exposeRequestAttributes(null, Collections.EMPTY_MAP);
}
}.runTest();
}
public void testExposeRequestAttributesWithNullAttributesMap() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.exposeRequestAttributes(new MockPortletRequest(), null);
}
}.runTest();
}
public void testExposeRequestAttributesWithAttributesMapContainingBadKeyType() throws Exception {
new AssertThrows(ClassCastException.class) {
public void test() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map attributes = new HashMap();
attributes.put(new Object(), "bad key type");
PortletUtils.exposeRequestAttributes(request, attributes);
}
}.runTest();
}
public void testExposeRequestAttributesSunnyDay() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map attributes = new HashMap();
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"));
}
public void testExposeRequestAttributesWithEmptyAttributesMapIsAnIdempotentOperation() throws Exception {
MockPortletRequest request = new MockPortletRequest();
Map attributes = new HashMap();
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()));
}
public void testGetOrCreateSessionAttributeWithNullSession() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getOrCreateSessionAttribute(null, "bean", TestBean.class);
}
}.runTest();
}
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);
}
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());
}
public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndNullClass() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", null);
}
}.runTest();
}
public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndClassThatIsAnInterfaceType() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", ITestBean.class);
}
}.runTest();
}
public void testGetOrCreateSessionAttributeWithNoExistingAttributeAndClassWithNoPublicCtor() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getOrCreateSessionAttribute(new MockPortletSession(), "bean", NoPublicCtor.class);
}
}.runTest();
}
public void testGetSessionMutexWithNullSession() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getSessionMutex(null);
}
}.runTest();
}
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);
}
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);
}
public void testGetSessionAttributeWithNullPortletRequest() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getSessionAttribute(null, "foo");
}
}.runTest();
}
public void testGetRequiredSessionAttributeWithNullPortletRequest() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.getRequiredSessionAttribute(null, "foo");
}
}.runTest();
}
public void testSetSessionAttributeWithNullPortletRequest() throws Exception {
new AssertThrows(IllegalArgumentException.class) {
public void test() throws Exception {
PortletUtils.setSessionAttribute(null, "foo", "bar");
}
}.runTest();
}
public void testGetSessionAttributeDoes_Not_CreateANewSession() throws Exception {
MockControl mock = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mock.getMock();
request.getPortletSession(false);
mock.setReturnValue(null);
mock.replay();
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNull("Must return null if session attribute does not exist (or if Session does not exist)", sessionAttribute);
mock.verify();
}
public void testGetSessionAttributeWithExistingSession() throws Exception {
MockControl mock = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mock.getMock();
request.getPortletSession(false);
MockPortletSession session = new MockPortletSession();
session.setAttribute("foo", "foo");
mock.setReturnValue(session);
mock.replay();
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
mock.verify();
}
public void testGetRequiredSessionAttributeWithExistingSession() throws Exception {
MockControl mock = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mock.getMock();
request.getPortletSession(false);
MockPortletSession session = new MockPortletSession();
session.setAttribute("foo", "foo");
mock.setReturnValue(session);
mock.replay();
Object sessionAttribute = PortletUtils.getRequiredSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
mock.verify();
}
public void testGetRequiredSessionAttributeWithExistingSessionAndNoAttribute() throws Exception {
MockControl mock = MockControl.createControl(PortletRequest.class);
final PortletRequest request = (PortletRequest) mock.getMock();
request.getPortletSession(false);
MockPortletSession session = new MockPortletSession();
mock.setReturnValue(session);
mock.replay();
new AssertThrows(IllegalStateException.class) {
public void test() throws Exception {
PortletUtils.getRequiredSessionAttribute(request, "foo");
}
}.runTest();
mock.verify();
}
public void testSetSessionAttributeWithExistingSessionAndNullValue() throws Exception {
MockControl mockSession = MockControl.createControl(PortletSession.class);
PortletSession session = (PortletSession) mockSession.getMock();
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(false); // must not create Session for null value...
mockRequest.setReturnValue(session);
session.removeAttribute("foo", PortletSession.APPLICATION_SCOPE);
mockSession.setVoidCallable();
mockRequest.replay();
mockSession.replay();
PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE);
mockRequest.verify();
mockSession.verify();
}
public void testSetSessionAttributeWithNoExistingSessionAndNullValue() throws Exception {
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(false); // must not create Session for null value...
mockRequest.setReturnValue(null);
mockRequest.replay();
PortletUtils.setSessionAttribute(request, "foo", null, PortletSession.APPLICATION_SCOPE);
mockRequest.verify();
}
public void testSetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
MockControl mockSession = MockControl.createControl(PortletSession.class);
PortletSession session = (PortletSession) mockSession.getMock();
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(); // must create Session...
mockRequest.setReturnValue(session);
session.setAttribute("foo", "foo", PortletSession.APPLICATION_SCOPE);
mockSession.setVoidCallable();
mockRequest.replay();
mockSession.replay();
PortletUtils.setSessionAttribute(request, "foo", "foo", PortletSession.APPLICATION_SCOPE);
mockRequest.verify();
mockSession.verify();
}
public void testGetSessionAttributeWithExistingSessionAndSpecificScope() throws Exception {
MockControl mockSession = MockControl.createControl(PortletSession.class);
PortletSession session = (PortletSession) mockSession.getMock();
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(false);
mockRequest.setReturnValue(session);
session.getAttribute("foo", PortletSession.APPLICATION_SCOPE);
mockSession.setReturnValue("foo");
mockRequest.replay();
mockSession.replay();
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);
mockRequest.verify();
mockSession.verify();
}
public void testGetSessionAttributeWithExistingSessionDefaultsToPortletScope() throws Exception {
MockControl mockSession = MockControl.createControl(PortletSession.class);
PortletSession session = (PortletSession) mockSession.getMock();
MockControl mockRequest = MockControl.createControl(PortletRequest.class);
PortletRequest request = (PortletRequest) mockRequest.getMock();
request.getPortletSession(false);
mockRequest.setReturnValue(session);
session.getAttribute("foo", PortletSession.PORTLET_SCOPE);
mockSession.setReturnValue("foo");
mockRequest.replay();
mockSession.replay();
Object sessionAttribute = PortletUtils.getSessionAttribute(request, "foo");
assertNotNull("Must not return null if session attribute exists (and Session exists)", sessionAttribute);
assertEquals("foo", sessionAttribute);
mockRequest.verify();
mockSession.verify();
}
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...");
}
}
}

View File

@@ -1,461 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.factory.config.RuntimeBeanReference;
import org.springframework.beans.factory.support.ManagedList;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.context.support.ApplicationObjectSupport;
import org.springframework.core.Ordered;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.context.request.WebRequestInterceptor;
import org.springframework.web.context.support.RequestHandledEvent;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.AbstractMultipartHttpServletRequest;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.springframework.web.servlet.handler.SimpleServletHandlerAdapter;
import org.springframework.web.servlet.handler.SimpleServletPostProcessor;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.handler.UserRoleAuthorizationInterceptor;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.ParameterizableViewController;
import org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.theme.SessionThemeResolver;
import org.springframework.web.servlet.theme.ThemeChangeInterceptor;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.ResourceBundleViewResolver;
/**
* @author Juergen Hoeller
* @since 21.05.2003
*/
public class ComplexWebApplicationContext extends StaticWebApplicationContext {
public void refresh() throws BeansException {
registerSingleton(DispatcherServlet.LOCALE_RESOLVER_BEAN_NAME, SessionLocaleResolver.class);
registerSingleton(DispatcherServlet.THEME_RESOLVER_BEAN_NAME, SessionThemeResolver.class);
LocaleChangeInterceptor interceptor1 = new LocaleChangeInterceptor();
LocaleChangeInterceptor interceptor2 = new LocaleChangeInterceptor();
interceptor2.setParamName("locale2");
ThemeChangeInterceptor interceptor3 = new ThemeChangeInterceptor();
ThemeChangeInterceptor interceptor4 = new ThemeChangeInterceptor();
interceptor4.setParamName("theme2");
UserRoleAuthorizationInterceptor interceptor5 = new UserRoleAuthorizationInterceptor();
interceptor5.setAuthorizedRoles(new String[] {"role1", "role2"});
List interceptors = new ArrayList();
interceptors.add(interceptor5);
interceptors.add(interceptor1);
interceptors.add(interceptor2);
interceptors.add(interceptor3);
interceptors.add(interceptor4);
interceptors.add(new MyHandlerInterceptor1());
interceptors.add(new MyHandlerInterceptor2());
interceptors.add(new MyWebRequestInterceptor());
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue(
"mappings", "/view.do=viewHandler\n/locale.do=localeHandler\nloc.do=anotherLocaleHandler");
pvs.addPropertyValue("interceptors", interceptors);
registerSingleton("myUrlMapping1", SimpleUrlHandlerMapping.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue(
"mappings", "/form.do=localeHandler\n/unknown.do=unknownHandler\nservlet.do=myServlet");
pvs.addPropertyValue("order", "2");
registerSingleton("myUrlMapping2", SimpleUrlHandlerMapping.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue(
"mappings", "/form.do=formHandler\n/head.do=headController\n" +
"body.do=bodyController\n/noview*=noviewController\n/noview/simple*=noviewController");
pvs.addPropertyValue("order", "1");
registerSingleton("handlerMapping", SimpleUrlHandlerMapping.class, pvs);
registerSingleton("myDummyAdapter", MyDummyAdapter.class);
registerSingleton("myHandlerAdapter", MyHandlerAdapter.class);
registerSingleton("standardHandlerAdapter", SimpleControllerHandlerAdapter.class);
registerSingleton("noviewController", NoViewController.class);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("order", new Integer(0));
pvs.addPropertyValue("basename", "org.springframework.web.servlet.complexviews");
registerSingleton("viewResolver", ResourceBundleViewResolver.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("suffix", ".jsp");
registerSingleton("viewResolver2", InternalResourceViewResolver.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("commandClass", "org.springframework.beans.TestBean");
pvs.addPropertyValue("formView", "form");
registerSingleton("formHandler", SimpleFormController.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("viewName", "form");
registerSingleton("viewHandler", ParameterizableViewController.class, pvs);
registerSingleton("localeHandler", ComplexLocaleChecker.class);
registerSingleton("anotherLocaleHandler", ComplexLocaleChecker.class);
registerSingleton("unknownHandler", Object.class);
registerSingleton("headController", HeadController.class);
registerSingleton("bodyController", BodyController.class);
registerSingleton("servletPostProcessor", SimpleServletPostProcessor.class);
registerSingleton("handlerAdapter", SimpleServletHandlerAdapter.class);
registerSingleton("myServlet", MyServlet.class);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("order", "1");
pvs.addPropertyValue("exceptionMappings",
"java.lang.IllegalAccessException=failed2\n" +
"ServletRequestBindingException=failed3");
pvs.addPropertyValue("defaultErrorView", "failed0");
registerSingleton("exceptionResolver1", SimpleMappingExceptionResolver.class, pvs);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("order", "0");
pvs.addPropertyValue("exceptionMappings", "java.lang.Exception=failed1");
List mappedHandlers = new ManagedList();
mappedHandlers.add(new RuntimeBeanReference("anotherLocaleHandler"));
pvs.addPropertyValue("mappedHandlers", mappedHandlers);
pvs.addPropertyValue("defaultStatusCode", "500");
pvs.addPropertyValue("defaultErrorView", "failed2");
registerSingleton("handlerExceptionResolver", SimpleMappingExceptionResolver.class, pvs);
registerSingleton("multipartResolver", MockMultipartResolver.class);
registerSingleton("testListener", TestApplicationListener.class);
addMessage("test", Locale.ENGLISH, "test message");
addMessage("test", Locale.CANADA, "Canadian & test message");
super.refresh();
}
public static class HeadController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
if ("HEAD".equals(request.getMethod())) {
response.setContentLength(5);
}
return null;
}
}
public static class BodyController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
response.getOutputStream().write("body".getBytes());
return null;
}
}
public static class NoViewController implements Controller {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
return new ModelAndView();
}
}
public static class MyServlet implements Servlet {
private ServletConfig servletConfig;
public void init(ServletConfig servletConfig) throws ServletException {
this.servletConfig = servletConfig;
}
public ServletConfig getServletConfig() {
return servletConfig;
}
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws IOException {
servletResponse.getOutputStream().write("body".getBytes());
}
public String getServletInfo() {
return null;
}
public void destroy() {
this.servletConfig = null;
}
}
public static interface MyHandler {
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException;
public long lastModified();
}
public static class MyHandlerAdapter extends ApplicationObjectSupport implements HandlerAdapter, Ordered {
public int getOrder() {
return 99;
}
public boolean supports(Object handler) {
return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
}
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object delegate)
throws ServletException, IllegalAccessException {
((MyHandler) delegate).doSomething(request);
return null;
}
public long getLastModified(HttpServletRequest request, Object delegate) {
return ((MyHandler) delegate).lastModified();
}
}
public static class MyDummyAdapter extends ApplicationObjectSupport implements HandlerAdapter {
public boolean supports(Object handler) {
return handler != null && MyHandler.class.isAssignableFrom(handler.getClass());
}
public ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object delegate)
throws IOException, ServletException {
throw new ServletException("dummy");
}
public long getLastModified(HttpServletRequest request, Object delegate) {
return -1;
}
}
public static class MyHandlerInterceptor1 implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException {
if (request.getAttribute("test2") != null) {
throw new ServletException("Wrong interceptor order");
}
request.setAttribute("test1", "test1");
request.setAttribute("test1x", "test1x");
request.setAttribute("test1y", "test1y");
return true;
}
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws ServletException {
if (request.getAttribute("test2x") != null) {
throw new ServletException("Wrong interceptor order");
}
if (!"test1x".equals(request.getAttribute("test1x"))) {
throw new ServletException("Incorrect request attribute");
}
request.removeAttribute("test1x");
}
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws ServletException {
if (request.getAttribute("test2y") != null) {
throw new ServletException("Wrong interceptor order");
}
request.removeAttribute("test1y");
}
}
public static class MyHandlerInterceptor2 implements HandlerInterceptor {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws ServletException {
if (request.getAttribute("test1x") == null) {
throw new ServletException("Wrong interceptor order");
}
if (request.getParameter("abort") != null) {
return false;
}
request.setAttribute("test2", "test2");
request.setAttribute("test2x", "test2x");
request.setAttribute("test2y", "test2y");
return true;
}
public void postHandle(
HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView)
throws ServletException {
if (request.getParameter("noView") != null) {
modelAndView.clear();
}
if (request.getAttribute("test1x") == null) {
throw new ServletException("Wrong interceptor order");
}
if (!"test2x".equals(request.getAttribute("test2x"))) {
throw new ServletException("Incorrect request attribute");
}
request.removeAttribute("test2x");
}
public void afterCompletion(
HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
if (request.getAttribute("test1y") == null) {
throw new ServletException("Wrong interceptor order");
}
request.removeAttribute("test2y");
}
}
public static class MyWebRequestInterceptor implements WebRequestInterceptor {
public void preHandle(WebRequest request) throws Exception {
request.setAttribute("test3", "test3", WebRequest.SCOPE_REQUEST);
}
public void postHandle(WebRequest request, ModelMap model) throws Exception {
request.setAttribute("test3x", "test3x", WebRequest.SCOPE_REQUEST);
}
public void afterCompletion(WebRequest request, Exception ex) throws Exception {
request.setAttribute("test3y", "test3y", WebRequest.SCOPE_REQUEST);
}
}
public static class ComplexLocaleChecker implements MyHandler {
public void doSomething(HttpServletRequest request) throws ServletException, IllegalAccessException {
WebApplicationContext wac = RequestContextUtils.getWebApplicationContext(request);
if (!(wac instanceof ComplexWebApplicationContext)) {
throw new ServletException("Incorrect WebApplicationContext");
}
if (!(request instanceof MultipartHttpServletRequest)) {
throw new ServletException("Not in a MultipartHttpServletRequest");
}
if (!(RequestContextUtils.getLocaleResolver(request) instanceof SessionLocaleResolver)) {
throw new ServletException("Incorrect LocaleResolver");
}
if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
throw new ServletException("Incorrect Locale");
}
if (!Locale.CANADA.equals(LocaleContextHolder.getLocale())) {
throw new ServletException("Incorrect Locale");
}
if (!(RequestContextUtils.getThemeResolver(request) instanceof SessionThemeResolver)) {
throw new ServletException("Incorrect ThemeResolver");
}
if (!"theme".equals(RequestContextUtils.getThemeResolver(request).resolveThemeName(request))) {
throw new ServletException("Incorrect theme name");
}
if (request.getParameter("fail") != null) {
throw new ModelAndViewDefiningException(new ModelAndView("failed1"));
}
if (request.getParameter("access") != null) {
throw new IllegalAccessException("illegal access");
}
if (request.getParameter("servlet") != null) {
throw new ServletRequestBindingException("servlet");
}
if (request.getParameter("exception") != null) {
throw new RuntimeException("servlet");
}
}
public long lastModified() {
return 99;
}
}
public static class MockMultipartResolver implements MultipartResolver {
public boolean isMultipart(HttpServletRequest request) {
return true;
}
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
if (request.getAttribute("fail") != null) {
throw new MaxUploadSizeExceededException(1000);
}
if (request instanceof MultipartHttpServletRequest) {
throw new IllegalStateException("Already a multipart request");
}
if (request.getAttribute("resolved") != null) {
throw new IllegalStateException("Already resolved");
}
request.setAttribute("resolved", Boolean.TRUE);
return new AbstractMultipartHttpServletRequest(request) {
};
}
public void cleanupMultipart(MultipartHttpServletRequest request) {
if (request.getAttribute("cleanedUp") != null) {
throw new IllegalStateException("Already cleaned up");
}
request.setAttribute("cleanedUp", Boolean.TRUE);
}
}
public static class TestApplicationListener implements ApplicationListener {
public int counter = 0;
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof RequestHandledEvent) {
this.counter++;
}
}
}
}

View File

@@ -1,118 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.BeansException;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.context.support.StaticMessageSource;
import org.springframework.ui.context.Theme;
import org.springframework.ui.context.ThemeSource;
import org.springframework.ui.context.support.SimpleTheme;
import org.springframework.ui.context.support.UiApplicationContextUtils;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.mvc.Controller;
import org.springframework.web.servlet.mvc.LastModified;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.theme.AbstractThemeResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
import org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping;
/**
* @author Juergen Hoeller
* @since 21.05.2003
*/
public class SimpleWebApplicationContext extends StaticWebApplicationContext {
public void refresh() throws BeansException {
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.addPropertyValue("commandClass", "org.springframework.beans.TestBean");
pvs.addPropertyValue("formView", "form");
registerSingleton("/form.do", SimpleFormController.class, pvs);
registerSingleton("/locale.do", LocaleChecker.class);
addMessage("test", Locale.ENGLISH, "test message");
addMessage("test", Locale.CANADA, "Canadian & test message");
addMessage("testArgs", Locale.ENGLISH, "test {0} message {1}");
addMessage("testArgsFormat", Locale.ENGLISH, "test {0} message {1,number,#.##} X");
registerSingleton(UiApplicationContextUtils.THEME_SOURCE_BEAN_NAME, DummyThemeSource.class);
registerSingleton("handlerMapping", BeanNameUrlHandlerMapping.class);
registerSingleton("viewResolver", InternalResourceViewResolver.class);
pvs = new MutablePropertyValues();
pvs.addPropertyValue("location", "org/springframework/web/context/WEB-INF/sessionContext.xml");
registerSingleton("viewResolver2", XmlViewResolver.class, pvs);
super.refresh();
}
public static class LocaleChecker implements Controller, LastModified {
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if (!(RequestContextUtils.getWebApplicationContext(request) instanceof SimpleWebApplicationContext)) {
throw new ServletException("Incorrect WebApplicationContext");
}
if (!(RequestContextUtils.getLocaleResolver(request) instanceof AcceptHeaderLocaleResolver)) {
throw new ServletException("Incorrect LocaleResolver");
}
if (!Locale.CANADA.equals(RequestContextUtils.getLocale(request))) {
throw new ServletException("Incorrect Locale");
}
return null;
}
public long getLastModified(HttpServletRequest request) {
return 98;
}
}
public static class DummyThemeSource implements ThemeSource {
private StaticMessageSource messageSource;
public DummyThemeSource() {
this.messageSource = new StaticMessageSource();
this.messageSource.addMessage("themetest", Locale.ENGLISH, "theme test message");
this.messageSource.addMessage("themetestArgs", Locale.ENGLISH, "theme test message {0}");
}
public Theme getTheme(String themeName) {
if (AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME.equals(themeName)) {
return new SimpleTheme(AbstractThemeResolver.ORIGINAL_DEFAULT_THEME_NAME, this.messageSource);
}
else {
return null;
}
}
}
}

View File

@@ -1,3 +0,0 @@
form.(class)=org.springframework.web.servlet.view.InternalResourceView
form.requestContextAttribute=rc
form.url=myform.jsp

View File

@@ -1,171 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.i18n;
import java.util.Locale;
import javax.servlet.http.Cookie;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* @author Alef Arendsen
* @author Juergen Hoeller
* @author Rick Evans
*/
public class CookieLocaleResolverTests extends TestCase {
public void testResolveLocale() {
MockHttpServletRequest request = new MockHttpServletRequest();
Cookie cookie = new Cookie("LanguageKoekje", "nl");
request.setCookies(new Cookie[]{cookie});
CookieLocaleResolver resolver = new CookieLocaleResolver();
// yup, koekje is the Dutch name for Cookie ;-)
resolver.setCookieName("LanguageKoekje");
Locale loc = resolver.resolveLocale(request);
assertEquals(loc.getLanguage(), "nl");
}
public void testSetAndResolveLocale() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setLocale(request, response, new Locale("nl", ""));
Cookie cookie = response.getCookie(CookieLocaleResolver.DEFAULT_COOKIE_NAME);
assertNotNull(cookie);
assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_NAME, cookie.getName());
assertEquals(null, cookie.getDomain());
assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_PATH, cookie.getPath());
assertEquals(CookieLocaleResolver.DEFAULT_COOKIE_MAX_AGE, cookie.getMaxAge());
assertFalse(cookie.getSecure());
request = new MockHttpServletRequest();
request.setCookies(new Cookie[]{cookie});
resolver = new CookieLocaleResolver();
Locale loc = resolver.resolveLocale(request);
assertEquals(loc.getLanguage(), "nl");
}
public void testCustomCookie() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setCookieName("LanguageKoek");
resolver.setCookieDomain(".springframework.org");
resolver.setCookiePath("/mypath");
resolver.setCookieMaxAge(10000);
resolver.setCookieSecure(true);
resolver.setLocale(request, response, new Locale("nl", ""));
Cookie cookie = response.getCookie("LanguageKoek");
assertNotNull(cookie);
assertEquals("LanguageKoek", cookie.getName());
assertEquals(".springframework.org", cookie.getDomain());
assertEquals("/mypath", cookie.getPath());
assertEquals(10000, cookie.getMaxAge());
assertTrue(cookie.getSecure());
request = new MockHttpServletRequest();
request.setCookies(new Cookie[]{cookie});
resolver = new CookieLocaleResolver();
resolver.setCookieName("LanguageKoek");
Locale loc = resolver.resolveLocale(request);
assertEquals(loc.getLanguage(), "nl");
}
public void testResolveLocaleWithoutCookie() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
CookieLocaleResolver resolver = new CookieLocaleResolver();
Locale locale = resolver.resolveLocale(request);
assertEquals(request.getLocale(), locale);
}
public void testResolveLocaleWithoutCookieAndDefaultLocale() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(Locale.GERMAN);
Locale locale = resolver.resolveLocale(request);
assertEquals(Locale.GERMAN, locale);
}
public void testResolveLocaleWithCookieWithoutLocale() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
Cookie cookie = new Cookie(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, "");
request.setCookies(new Cookie[]{cookie});
CookieLocaleResolver resolver = new CookieLocaleResolver();
Locale locale = resolver.resolveLocale(request);
assertEquals(request.getLocale(), locale);
}
public void testSetLocaleToNullLocale() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
Cookie cookie = new Cookie(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, Locale.UK.toString());
request.setCookies(new Cookie[]{cookie});
MockHttpServletResponse response = new MockHttpServletResponse();
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setLocale(request, response, null);
Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME);
assertEquals(Locale.TAIWAN, locale);
Cookie[] cookies = response.getCookies();
assertEquals(1, cookies.length);
Cookie localeCookie = cookies[0];
assertEquals(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, localeCookie.getName());
assertEquals("", localeCookie.getValue());
}
public void testSetLocaleToNullLocaleWithDefault() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
Cookie cookie = new Cookie(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, Locale.UK.toString());
request.setCookies(new Cookie[]{cookie});
MockHttpServletResponse response = new MockHttpServletResponse();
CookieLocaleResolver resolver = new CookieLocaleResolver();
resolver.setDefaultLocale(Locale.CANADA_FRENCH);
resolver.setLocale(request, response, null);
Locale locale = (Locale) request.getAttribute(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME);
assertEquals(Locale.CANADA_FRENCH, locale);
Cookie[] cookies = response.getCookies();
assertEquals(1, cookies.length);
Cookie localeCookie = cookies[0];
assertEquals(CookieLocaleResolver.LOCALE_REQUEST_ATTRIBUTE_NAME, localeCookie.getName());
assertEquals("", localeCookie.getValue());
}
}

View File

@@ -1,70 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.i18n;
import java.util.Locale;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.servlet.LocaleResolver;
/**
* @author Juergen Hoeller
* @since 20.03.2003
*/
public class LocaleResolverTests extends TestCase {
private void internalTest(LocaleResolver localeResolver, boolean shouldSet) {
// create mocks
MockServletContext context = new MockServletContext();
MockHttpServletRequest request = new MockHttpServletRequest(context);
request.addPreferredLocale(Locale.UK);
MockHttpServletResponse response = new MockHttpServletResponse();
// check original locale
Locale locale = localeResolver.resolveLocale(request);
assertEquals(locale, Locale.UK);
// set new locale
try {
localeResolver.setLocale(request, response, Locale.GERMANY);
if (!shouldSet)
fail("should not be able to set Locale");
// check new locale
locale = localeResolver.resolveLocale(request);
assertEquals(locale, Locale.GERMANY);
}
catch (UnsupportedOperationException ex) {
if (shouldSet)
fail("should be able to set Locale");
}
}
public void testAcceptHeaderLocaleResolver() {
internalTest(new AcceptHeaderLocaleResolver(), false);
}
public void testCookieLocaleResolver() {
internalTest(new CookieLocaleResolver(), true);
}
public void testSessionLocaleResolver() {
internalTest(new SessionLocaleResolver(), true);
}
}

View File

@@ -1,95 +0,0 @@
/*
* 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.servlet.i18n;
import java.util.Locale;
import javax.servlet.http.HttpSession;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* @author Juergen Hoeller
*/
public class SessionLocaleResolverTests extends TestCase {
public void testResolveLocale() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.GERMAN);
SessionLocaleResolver resolver = new SessionLocaleResolver();
assertEquals(Locale.GERMAN, resolver.resolveLocale(request));
}
public void testSetAndResolveLocale() {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setLocale(request, response, Locale.GERMAN);
assertEquals(Locale.GERMAN, resolver.resolveLocale(request));
HttpSession session = request.getSession();
request = new MockHttpServletRequest();
request.setSession(session);
resolver = new SessionLocaleResolver();
assertEquals(Locale.GERMAN, resolver.resolveLocale(request));
}
public void testResolveLocaleWithoutSession() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
SessionLocaleResolver resolver = new SessionLocaleResolver();
assertEquals(request.getLocale(), resolver.resolveLocale(request));
}
public void testResolveLocaleWithoutSessionAndDefaultLocale() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setDefaultLocale(Locale.GERMAN);
assertEquals(Locale.GERMAN, resolver.resolveLocale(request));
}
public void testSetLocaleToNullLocale() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, Locale.GERMAN);
MockHttpServletResponse response = new MockHttpServletResponse();
SessionLocaleResolver resolver = new SessionLocaleResolver();
resolver.setLocale(request, response, null);
Locale locale = (Locale) request.getSession().getAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME);
assertNull(locale);
HttpSession session = request.getSession();
request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.TAIWAN);
request.setSession(session);
resolver = new SessionLocaleResolver();
assertEquals(Locale.TAIWAN, resolver.resolveLocale(request));
}
}

View File

@@ -1,284 +0,0 @@
/*
* 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.servlet.view;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
/**
* Tests for AbstractView. Not called AbstractViewTests as
* would otherwise be excluded by Ant build script wildcard.
*
* @author Rod Johnson
*/
public class BaseViewTests extends TestCase {
public void testRenderWithoutStaticAttributes() throws Exception {
MockControl mc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) mc.getMock();
wac.getServletContext();
mc.setReturnValue(new MockServletContext());
mc.replay();
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
TestView tv = new TestView(request, response, wac);
// Check superclass handles duplicate init
tv.setApplicationContext(wac);
tv.setApplicationContext(wac);
Map model = new HashMap();
model.put("foo", "bar");
model.put("something", new Object());
tv.render(model, request, response);
// check it contains all
checkContainsAll(model, tv.model);
assertTrue(tv.inited);
mc.verify();
}
/**
* Test attribute passing, NOT CSV parsing.
*/
public void testRenderWithStaticAttributesNoCollision() throws Exception {
MockControl mc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) mc.getMock();
wac.getServletContext();
mc.setReturnValue(new MockServletContext());
mc.replay();
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
TestView tv = new TestView(request, response, wac);
tv.setApplicationContext(wac);
Properties p = new Properties();
p.setProperty("foo", "bar");
p.setProperty("something", "else");
tv.setAttributes(p);
Map model = new HashMap();
model.put("one", new HashMap());
model.put("two", new Object());
tv.render(model, request, response);
// Check it contains all
checkContainsAll(model, tv.model);
checkContainsAll(p, tv.model);
assertTrue(tv.inited);
mc.verify();
}
public void testDynamicModelOverridesStaticAttributesIfCollision() throws Exception {
MockControl mc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) mc.getMock();
wac.getServletContext();
mc.setReturnValue(new MockServletContext());
mc.replay();
HttpServletRequest request = new MockHttpServletRequest();
HttpServletResponse response = new MockHttpServletResponse();
TestView tv = new TestView(request, response, wac);
tv.setApplicationContext(wac);
Properties p = new Properties();
p.setProperty("one", "bar");
p.setProperty("something", "else");
tv.setAttributes(p);
Map model = new HashMap();
model.put("one", new HashMap());
model.put("two", new Object());
tv.render(model, request, response);
// Check it contains all
checkContainsAll(model, tv.model);
assertTrue(tv.model.size() == 3);
// will have old something from properties
assertTrue(tv.model.get("something").equals("else"));
assertTrue(tv.inited);
mc.verify();
}
public void testIgnoresNullAttributes() {
AbstractView v = new ConcreteView();
v.setAttributes(null);
assertTrue(v.getStaticAttributes().size() == 0);
}
/**
* Test only the CSV parsing implementation.
*/
public void testAttributeCSVParsingIgnoresNull() {
AbstractView v = new ConcreteView();
v.setAttributesCSV(null);
assertTrue(v.getStaticAttributes().size() == 0);
}
public void testAttributeCSVParsingIgnoresEmptyString() {
AbstractView v = new ConcreteView();
v.setAttributesCSV("");
assertTrue(v.getStaticAttributes().size() == 0);
}
/**
* Format is attname0={value1},attname1={value1}
*/
public void testAttributeCSVParsingValid() {
AbstractView v = new ConcreteView();
v.setAttributesCSV("foo=[bar],king=[kong]");
assertTrue(v.getStaticAttributes().size() == 2);
assertTrue(v.getStaticAttributes().get("foo").equals("bar"));
assertTrue(v.getStaticAttributes().get("king").equals("kong"));
}
public void testAttributeCSVParsingValidWithWeirdCharacters() {
AbstractView v = new ConcreteView();
String fooval = "owfie fue&3[][[[2 \n\n \r \t 8<>3";
// Also tests empty value
String kingval = "";
v.setAttributesCSV("foo=(" + fooval + "),king={" + kingval + "},f1=[we]");
assertTrue(v.getStaticAttributes().size() == 3);
assertTrue(v.getStaticAttributes().get("foo").equals(fooval));
assertTrue(v.getStaticAttributes().get("king").equals(kingval));
}
public void testAttributeCSVParsingInvalid() {
AbstractView v = new ConcreteView();
try {
// No equals
v.setAttributesCSV("fweoiruiu");
fail();
}
catch (IllegalArgumentException ex) {
}
try {
// No value
v.setAttributesCSV("fweoiruiu=");
fail();
}
catch (IllegalArgumentException ex) {
}
try {
// No closing ]
v.setAttributesCSV("fweoiruiu=[");
fail();
}
catch (IllegalArgumentException ex) {
}
try {
// Second one is bogus
v.setAttributesCSV("fweoiruiu=[de],=");
fail();
}
catch (IllegalArgumentException ex) {
}
}
public void testAttributeCSVParsingIgoresTrailingComma() {
AbstractView v = new ConcreteView();
v.setAttributesCSV("foo=[de],");
assertTrue(v.getStaticAttributes().size() == 1);
}
/**
* Check that all keys in expected have same values in actual
* @param expected
* @param actual
*/
private void checkContainsAll(Map expected, Map actual) {
Set keys = expected.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
String key = (String) iter.next();
//System.out.println("Checking model key " + key);
assertTrue("Value for model key '" + key + "' must match", actual.get(key) == expected.get(key));
}
}
/**
* Trivial concrete subclass we can use when we're interested only
* in CSV parsing, which doesn't require lifecycle management
*/
private class ConcreteView extends AbstractView {
// Do-nothing concrete subclass
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
throw new UnsupportedOperationException();
}
}
/**
* Single threaded subclass of AbstractView to check superclass
* behaviour
*/
private class TestView extends AbstractView {
private HttpServletRequest request;
private HttpServletResponse response;
private WebApplicationContext wac;
public boolean inited;
/** Captured model in render */
public Map model;
public TestView(HttpServletRequest request, HttpServletResponse response, WebApplicationContext wac) {
this.request = request;
this.response = response;
this.wac = wac;
}
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// do nothing
this.model = model;
}
/**
* @see org.springframework.context.support.ApplicationObjectSupport#initApplicationContext()
*/
protected void initApplicationContext() throws ApplicationContextException {
if (inited)
throw new RuntimeException("Already initialized");
this.inited = true;
assertTrue(getApplicationContext() == wac);
}
}
}

View File

@@ -1,114 +0,0 @@
/*
* 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.servlet.view;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
/**
* Unit tests for the DefaultRequestToViewNameTranslator class.
*
* @author Rick Evans
*/
public final class DefaultRequestToViewNameTranslatorTests extends TestCase {
private static final String VIEW_NAME = "apple";
private static final String EXTENSION = ".html";
private static final String CONTEXT_PATH = "/sundays";
private DefaultRequestToViewNameTranslator translator;
private MockHttpServletRequest request;
protected void setUp() throws Exception {
this.translator = new DefaultRequestToViewNameTranslator();
this.request = new MockHttpServletRequest();
this.request.setContextPath(CONTEXT_PATH);
}
public void TODO_testGetViewNameLeavesLeadingSlashIfSoConfigured() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME);
this.translator.setStripLeadingSlash(false);
assertViewName("/" + VIEW_NAME);
}
public void testGetViewNameLeavesExtensionIfSoConfigured() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME + EXTENSION);
this.translator.setStripExtension(false);
assertViewName(VIEW_NAME + EXTENSION);
}
public void testGetViewNameWithDefaultConfiguration() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME + EXTENSION);
assertViewName(VIEW_NAME);
}
public void testGetViewNameWithCustomSeparator() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME + "/fiona" + EXTENSION);
this.translator.setSeparator("_");
assertViewName(VIEW_NAME + "_fiona");
}
public void testGetViewNameWithNoExtension() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME);
assertViewName(VIEW_NAME);
}
public void testGetViewNameWithPrefix() throws Exception {
final String prefix = "fiona_";
request.setRequestURI(CONTEXT_PATH + VIEW_NAME);
this.translator.setPrefix(prefix);
assertViewName(prefix + VIEW_NAME);
}
public void testGetViewNameWithNullPrefix() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME);
this.translator.setPrefix(null);
assertViewName(VIEW_NAME);
}
public void testGetViewNameWithSuffix() throws Exception {
final String suffix = ".fiona";
request.setRequestURI(CONTEXT_PATH + VIEW_NAME);
this.translator.setSuffix(suffix);
assertViewName(VIEW_NAME + suffix);
}
public void testGetViewNameWithNullSuffix() throws Exception {
request.setRequestURI(CONTEXT_PATH + VIEW_NAME);
this.translator.setSuffix(null);
assertViewName(VIEW_NAME);
}
public void testTrySetUrlPathHelperToNull() throws Exception {
try {
this.translator.setUrlPathHelper(null);
}
catch (IllegalArgumentException expected) {
}
}
private void assertViewName(String expectedViewName) {
String actualViewName = this.translator.getViewName(this.request);
assertNotNull(actualViewName);
assertEquals("Did not get the expected viewName from the DefaultRequestToViewNameTranslator.getViewName(..)",
expectedViewName, actualViewName);
}
}

View File

@@ -1,146 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.TestBean;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;
/**
* Dummy request context used for VTL and FTL macro tests.
*
* @author Darren Davison
* @author Juergen Hoeller
* @since 25.01.2005
* @see org.springframework.web.servlet.support.RequestContext
*/
public class DummyMacroRequestContext {
private HttpServletRequest request;
private Map messageMap;
private Map themeMessageMap;
private String contextPath;
public DummyMacroRequestContext(HttpServletRequest request) {
this.request = request;
}
public void setMessageMap(Map messageMap) {
this.messageMap = messageMap;
}
public void setThemeMessageMap(Map themeMessageMap) {
this.themeMessageMap = themeMessageMap;
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getMessage(String)
*/
public String getMessage(String code) {
return (String) this.messageMap.get(code);
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getMessage(String, String)
*/
public String getMessage(String code, String defaultMsg) {
String msg = (String) this.messageMap.get(code);
return (msg != null ? msg : defaultMsg);
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getMessage(String, List)
*/
public String getMessage(String code, List args) {
return ((String) this.messageMap.get(code)) + args.toString();
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getMessage(String, List, String)
*/
public String getMessage(String code, List args, String defaultMsg) {
String msg = (String) this.messageMap.get(code);
return (msg != null ? msg + args.toString(): defaultMsg);
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getThemeMessage(String)
*/
public String getThemeMessage(String code) {
return (String) this.themeMessageMap.get(code);
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getThemeMessage(String, String)
*/
public String getThemeMessage(String code, String defaultMsg) {
String msg = (String) this.themeMessageMap.get(code);
return (msg != null ? msg : defaultMsg);
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getThemeMessage(String, List)
*/
public String getThemeMessage(String code, List args) {
return ((String) this.themeMessageMap.get(code)) + args.toString();
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getThemeMessage(String, List, String)
*/
public String getThemeMessage(String code, List args, String defaultMsg) {
String msg = (String) this.themeMessageMap.get(code);
return (msg != null ? msg + args.toString(): defaultMsg);
}
public void setContextPath(String contextPath) {
this.contextPath = contextPath;
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getContextPath()
*/
public String getContextPath() {
return this.contextPath;
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getBindStatus(String)
*/
public BindStatus getBindStatus(String path) throws IllegalStateException {
return new BindStatus(new RequestContext(this.request), path, false);
}
/**
* @see org.springframework.web.servlet.support.RequestContext#getBindStatus(String, boolean)
*/
public BindStatus getBindStatus(String path, boolean htmlEscape) throws IllegalStateException {
return new BindStatus(new RequestContext(this.request), path, true);
}
}

View File

@@ -1,237 +0,0 @@
/*
* 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.servlet.view;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockRequestDispatcher;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.util.WebUtils;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class InternalResourceViewTests extends TestCase {
/**
* Test that if the url property isn't supplied, view initialization fails.
*/
public void testRejectsNullUrl() throws Exception {
InternalResourceView view = new InternalResourceView();
try {
view.afterPropertiesSet();
fail("Should be forced to set URL");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testForward() throws Exception {
HashMap model = new HashMap();
Object obj = new Integer(1);
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myservlet/handler.do");
request.setContextPath("/mycontext");
request.setServletPath("/myservlet");
request.setPathInfo(";mypathinfo");
request.setQueryString("?param1=value1");
InternalResourceView view = new InternalResourceView();
view.setUrl(url);
view.setServletContext(new MockServletContext() {
public int getMinorVersion() {
return 4;
}
});
MockHttpServletResponse response = new MockHttpServletResponse();
view.render(model, request, response);
assertEquals(url, response.getForwardedUrl());
Set keys = model.keySet();
for (Iterator it = keys.iterator(); it.hasNext();) {
String key = (String) it.next();
assertEquals(model.get(key), request.getAttribute(key));
}
assertEquals("/myservlet/handler.do", request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE));
assertEquals("/mycontext", request.getAttribute(WebUtils.FORWARD_CONTEXT_PATH_ATTRIBUTE));
assertEquals("/myservlet", request.getAttribute(WebUtils.FORWARD_SERVLET_PATH_ATTRIBUTE));
assertEquals(";mypathinfo", request.getAttribute(WebUtils.FORWARD_PATH_INFO_ATTRIBUTE));
assertEquals("?param1=value1", request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE));
}
public void testForwardWithForwardAttributesPresent() throws Exception {
HashMap model = new HashMap();
Object obj = new Integer(1);
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/myservlet/handler.do");
request.setContextPath("/mycontext");
request.setServletPath("/myservlet");
request.setPathInfo(";mypathinfo");
request.setQueryString("?param1=value1");
request.setAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE, "/MYservlet/handler.do");
request.setAttribute(WebUtils.FORWARD_CONTEXT_PATH_ATTRIBUTE, "/MYcontext");
request.setAttribute(WebUtils.FORWARD_SERVLET_PATH_ATTRIBUTE, "/MYservlet");
request.setAttribute(WebUtils.FORWARD_PATH_INFO_ATTRIBUTE, ";MYpathinfo");
request.setAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE, "?Param1=value1");
InternalResourceView view = new InternalResourceView();
view.setUrl(url);
view.setServletContext(new MockServletContext() {
public int getMinorVersion() {
return 4;
}
});
MockHttpServletResponse response = new MockHttpServletResponse();
view.render(model, request, response);
assertEquals(url, response.getForwardedUrl());
Set keys = model.keySet();
for (Iterator it = keys.iterator(); it.hasNext();) {
String key = (String) it.next();
assertEquals(model.get(key), request.getAttribute(key));
}
assertEquals("/MYservlet/handler.do", request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE));
assertEquals("/MYcontext", request.getAttribute(WebUtils.FORWARD_CONTEXT_PATH_ATTRIBUTE));
assertEquals("/MYservlet", request.getAttribute(WebUtils.FORWARD_SERVLET_PATH_ATTRIBUTE));
assertEquals(";MYpathinfo", request.getAttribute(WebUtils.FORWARD_PATH_INFO_ATTRIBUTE));
assertEquals("?Param1=value1", request.getAttribute(WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE));
}
public void testAlwaysInclude() throws Exception {
HashMap model = new HashMap();
Object obj = new Integer(1);
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
MockControl reqControl = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) reqControl.getMock();
Set keys = model.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
String key = (String) iter.next();
request.setAttribute(key, model.get(key));
reqControl.setVoidCallable(1);
}
request.getRequestDispatcher(url);
reqControl.setReturnValue(new MockRequestDispatcher(url));
reqControl.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
InternalResourceView v = new InternalResourceView();
v.setUrl(url);
v.setAlwaysInclude(true);
// Can now try multiple tests
v.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
reqControl.verify();
}
public void testIncludeOnAttribute() throws Exception {
HashMap model = new HashMap();
Object obj = new Integer(1);
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
MockControl reqControl = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) reqControl.getMock();
Set keys = model.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
String key = (String) iter.next();
request.setAttribute(key, model.get(key));
reqControl.setVoidCallable(1);
}
request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
reqControl.setReturnValue("somepath");
request.getRequestDispatcher(url);
reqControl.setReturnValue(new MockRequestDispatcher(url));
reqControl.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
InternalResourceView v = new InternalResourceView();
v.setUrl(url);
// Can now try multiple tests
v.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
reqControl.verify();
}
public void testIncludeOnCommitted() throws Exception {
HashMap model = new HashMap();
Object obj = new Integer(1);
model.put("foo", "bar");
model.put("I", obj);
String url = "forward-to";
MockControl reqControl = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) reqControl.getMock();
Set keys = model.keySet();
for (Iterator iter = keys.iterator(); iter.hasNext();) {
String key = (String) iter.next();
request.setAttribute(key, model.get(key));
reqControl.setVoidCallable(1);
}
request.getAttribute(WebUtils.INCLUDE_REQUEST_URI_ATTRIBUTE);
reqControl.setReturnValue(null);
request.getRequestDispatcher(url);
reqControl.setReturnValue(new MockRequestDispatcher(url));
reqControl.replay();
MockHttpServletResponse response = new MockHttpServletResponse();
response.setCommitted(true);
InternalResourceView v = new InternalResourceView();
v.setUrl(url);
// Can now try multiple tests
v.render(model, request, response);
assertEquals(url, response.getIncludedUrl());
reqControl.verify();
}
}

View File

@@ -1,235 +0,0 @@
/*
* 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.servlet.view;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.AssertionFailedError;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* Tests for redirect view, and query string construction.
* Doesn't test URL encoding, although it does check that it's called.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @author Sam Brannen
* @since 27.05.2003
*/
public class RedirectViewTests extends TestCase {
public void testNoUrlSet() throws Exception {
RedirectView rv = new RedirectView();
try {
rv.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testHttp11() throws Exception {
RedirectView rv = new RedirectView();
rv.setUrl("http://url.somewhere.com");
rv.setHttp10Compatible(false);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
rv.render(new HashMap(), request, response);
assertEquals(303, response.getStatus());
assertEquals("http://url.somewhere.com", response.getHeader("Location"));
}
public void testEmptyMap() throws Exception {
String url = "/myUrl";
doTest(new HashMap(), url, false, url);
}
public void testEmptyMapWithContextRelative() throws Exception {
String url = "/myUrl";
doTest(new HashMap(), url, true, url);
}
public void testSingleParam() throws Exception {
String url = "http://url.somewhere.com";
String key = "foo";
String val = "bar";
Map model = new HashMap();
model.put(key, val);
String expectedUrlForEncoding = url + "?" + key + "=" + val;
doTest(model, url, false, expectedUrlForEncoding);
}
public void testSingleParamWithoutExposingModelAttributes() throws Exception {
String url = "http://url.somewhere.com";
String key = "foo";
String val = "bar";
Map model = new HashMap();
model.put(key, val);
String expectedUrlForEncoding = url; // + "?" + key + "=" + val;
doTest(model, url, false, false, expectedUrlForEncoding);
}
public void testParamWithAnchor() throws Exception {
String url = "http://url.somewhere.com/test.htm#myAnchor";
String key = "foo";
String val = "bar";
Map model = new HashMap();
model.put(key, val);
String expectedUrlForEncoding = "http://url.somewhere.com/test.htm" + "?" + key + "=" + val + "#myAnchor";
doTest(model, url, false, expectedUrlForEncoding);
}
public void testTwoParams() throws Exception {
String url = "http://url.somewhere.com";
String key = "foo";
String val = "bar";
String key2 = "thisIsKey2";
String val2 = "andThisIsVal2";
Map model = new HashMap();
model.put(key, val);
model.put(key2, val2);
try {
String expectedUrlForEncoding = "http://url.somewhere.com?" + key + "=" + val + "&" + key2 + "=" + val2;
doTest(model, url, false, expectedUrlForEncoding);
}
catch (AssertionFailedError err) {
// OK, so it's the other order... probably on Sun JDK 1.6 or IBM JDK 1.5
String expectedUrlForEncoding = "http://url.somewhere.com?" + key2 + "=" + val2 + "&" + key + "=" + val;
doTest(model, url, false, expectedUrlForEncoding);
}
}
public void testArrayParam() throws Exception {
String url = "http://url.somewhere.com";
String key = "foo";
String[] val = new String[] {"bar", "baz"};
Map model = new HashMap();
model.put(key, val);
try {
String expectedUrlForEncoding = "http://url.somewhere.com?" + key + "=" + val[0] + "&" + key + "=" + val[1];
doTest(model, url, false, expectedUrlForEncoding);
}
catch (AssertionFailedError err) {
// OK, so it's the other order... probably on Sun JDK 1.6 or IBM JDK 1.5
String expectedUrlForEncoding = "http://url.somewhere.com?" + key + "=" + val[1] + "&" + key + "=" + val[0];
doTest(model, url, false, expectedUrlForEncoding);
}
}
public void testCollectionParam() throws Exception {
String url = "http://url.somewhere.com";
String key = "foo";
List val = new ArrayList();
val.add("bar");
val.add("baz");
Map model = new HashMap();
model.put(key, val);
try {
String expectedUrlForEncoding = "http://url.somewhere.com?" + key + "=" + val.get(0) + "&" + key + "=" + val.get(1);
doTest(model, url, false, expectedUrlForEncoding);
}
catch (AssertionFailedError err) {
// OK, so it's the other order... probably on Sun JDK 1.6 or IBM JDK 1.5
String expectedUrlForEncoding = "http://url.somewhere.com?" + key + "=" + val.get(1) + "&" + key + "=" + val.get(0);
doTest(model, url, false, expectedUrlForEncoding);
}
}
public void testObjectConversion() throws Exception {
String url = "http://url.somewhere.com";
String key = "foo";
String val = "bar";
String key2 = "int2";
Object val2 = new Long(611);
Object key3 = "tb";
Object val3 = new TestBean();
Map model = new LinkedHashMap();
model.put(key, val);
model.put(key2, val2);
model.put(key3, val3);
String expectedUrlForEncoding = "http://url.somewhere.com?" + key + "=" + val + "&" + key2 + "=" + val2;
doTest(model, url, false, expectedUrlForEncoding);
}
private void doTest(Map map, String url, boolean contextRelative, String expectedUrlForEncoding)
throws Exception {
doTest(map, url, contextRelative, true, expectedUrlForEncoding);
}
private void doTest(final Map map, final String url, final boolean contextRelative,
final boolean exposeModelAttributes, String expectedUrlForEncoding) throws Exception {
class TestRedirectView extends RedirectView {
public boolean queryPropertiesCalled = false;
/**
* Test whether this callback method is called with correct args
*/
protected Map queryProperties(Map model) {
// They may not be the same model instance, but they're still equal
assertTrue("Map and model must be equal.", map.equals(model));
this.queryPropertiesCalled = true;
return super.queryProperties(model);
}
}
TestRedirectView rv = new TestRedirectView();
rv.setUrl(url);
rv.setContextRelative(contextRelative);
rv.setExposeModelAttributes(exposeModelAttributes);
MockControl requestControl = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest request = (HttpServletRequest) requestControl.getMock();
request.getCharacterEncoding();
requestControl.setReturnValue(null, 1);
if (contextRelative) {
expectedUrlForEncoding = "/context" + expectedUrlForEncoding;
request.getContextPath();
requestControl.setReturnValue("/context");
}
requestControl.replay();
MockControl responseControl = MockControl.createControl(HttpServletResponse.class);
HttpServletResponse resp = (HttpServletResponse) responseControl.getMock();
resp.encodeRedirectURL(expectedUrlForEncoding);
responseControl.setReturnValue(expectedUrlForEncoding);
resp.sendRedirect(expectedUrlForEncoding);
responseControl.setVoidCallable(1);
responseControl.replay();
rv.render(map, request, resp);
if (exposeModelAttributes) {
assertTrue("queryProperties() should have been called.", rv.queryPropertiesCalled);
}
responseControl.verify();
}
}

View File

@@ -1,28 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view;
/**
* @author Rod Johnson
*/
public class ResourceBundleViewResolverNoCacheTests extends ResourceBundleViewResolverTests {
protected boolean getCache() {
return false;
}
}

View File

@@ -1,181 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view;
import java.util.Locale;
import java.util.Map;
import java.util.MissingResourceException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.springframework.beans.factory.BeanIsAbstractException;
import org.springframework.core.io.Resource;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.View;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class ResourceBundleViewResolverTests extends TestCase {
/** Comes from this package */
private static String PROPS_FILE = "org.springframework.web.servlet.view.testviews";
private ResourceBundleViewResolver rb;
private StaticWebApplicationContext wac;
protected void setUp() throws Exception {
rb = new ResourceBundleViewResolver();
rb.setBasename(PROPS_FILE);
rb.setCache(getCache());
rb.setDefaultParentView("testParent");
wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
wac.refresh();
// This will be propagated to views, so we need it.
rb.setApplicationContext(wac);
}
/**
* Not a constant: allows overrides.
* Controls whether to cache views.
*/
protected boolean getCache() {
return true;
}
public void testParentsAreAbstract() throws Exception {
try {
View v = rb.resolveViewName("debug.Parent", Locale.ENGLISH);
fail("Should have thrown BeanIsAbstractException");
}
catch (BeanIsAbstractException ex) {
// expected
}
try {
View v = rb.resolveViewName("testParent", Locale.ENGLISH);
fail("Should have thrown BeanIsAbstractException");
}
catch (BeanIsAbstractException ex) {
// expected
}
}
public void testDebugViewEnglish() throws Exception {
View v = rb.resolveViewName("debugView", Locale.ENGLISH);
assertTrue("debugView must be of type InternalResourceView", v instanceof InternalResourceView);
InternalResourceView jv = (InternalResourceView) v;
assertTrue("debugView must have correct URL", "jsp/debug/debug.jsp".equals(jv.getUrl()));
Map m = jv.getStaticAttributes();
assertTrue("Must have 2 static attributes, not " + m.size(), m.size() == 2);
assertTrue("attribute foo = bar, not '" + m.get("foo") + "'", m.get("foo").equals("bar"));
assertTrue("attribute postcode = SE10 9JY", m.get("postcode").equals("SE10 9JY"));
assertTrue("Correct default content type", jv.getContentType().equals(AbstractView.DEFAULT_CONTENT_TYPE));
}
public void testDebugViewFrench() throws Exception {
View v = rb.resolveViewName("debugView", Locale.FRENCH);
assertTrue("French debugView must be of type InternalResourceView", v instanceof InternalResourceView);
InternalResourceView jv = (InternalResourceView) v;
assertTrue("French debugView must have correct URL", "jsp/debug/deboug.jsp".equals(jv.getUrl()));
assertTrue(
"Correct overridden (XML) content type, not '" + jv.getContentType() + "'",
jv.getContentType().equals("text/xml;charset=ISO-8859-1"));
}
public void testEagerInitialization() throws Exception {
ResourceBundleViewResolver rb = new ResourceBundleViewResolver();
rb.setBasename(PROPS_FILE);
rb.setCache(getCache());
rb.setDefaultParentView("testParent");
rb.setLocalesToInitialize(new Locale[] {Locale.ENGLISH, Locale.FRENCH});
rb.setApplicationContext(wac);
View v = rb.resolveViewName("debugView", Locale.FRENCH);
assertTrue("French debugView must be of type InternalResourceView", v instanceof InternalResourceView);
InternalResourceView jv = (InternalResourceView) v;
assertTrue("French debugView must have correct URL", "jsp/debug/deboug.jsp".equals(jv.getUrl()));
assertTrue(
"Correct overridden (XML) content type, not '" + jv.getContentType() + "'",
jv.getContentType().equals("text/xml;charset=ISO-8859-1"));
}
public void testSameBundleOnlyCachedOnce() throws Exception {
if (rb.isCache()) {
View v1 = rb.resolveViewName("debugView", Locale.ENGLISH);
View v2 = rb.resolveViewName("debugView", Locale.UK);
assertSame(v1, v2);
}
}
public void testNoSuchViewEnglish() throws Exception {
View v = rb.resolveViewName("xxxxxxweorqiwuopeir", Locale.ENGLISH);
assertTrue(v == null);
}
public void testOnSetContextCalledOnce() throws Exception {
TestView tv = (TestView) rb.resolveViewName("test", Locale.ENGLISH);
tv = (TestView) rb.resolveViewName("test", Locale.ENGLISH);
tv = (TestView) rb.resolveViewName("test", Locale.ENGLISH);
assertTrue("test has correct name", "test".equals(tv.getBeanName()));
assertTrue("test should have been initialized once, not " + tv.initCount + " times", tv.initCount == 1);
}
public void testNoSuchBasename() throws Exception {
try {
rb.setBasename("weoriwoierqupowiuer");
View v = rb.resolveViewName("debugView", Locale.ENGLISH);
fail("No such basename: all requests should fail with exception");
}
catch (MissingResourceException ex) {
// OK
}
}
public static class TestView extends AbstractView {
public int initCount;
public void setLocation(Resource location) {
if (!(location instanceof ServletContextResource)) {
throw new IllegalArgumentException("Expecting ServletContextResource, not " + location.getClass().getName());
}
}
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response) {
}
protected void initApplicationContext() {
++initCount;
}
}
}

View File

@@ -1,331 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.document;
import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
/**
* Tests for the AbstractExcelView and the AbstractJExcelView classes.
*
* @author Alef Arendsen
* @author Bram Smeets
*/
public class ExcelViewTests extends TestCase {
private MockServletContext servletCtx;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private StaticWebApplicationContext webAppCtx;
public void setUp() {
servletCtx = new MockServletContext("org/springframework/web/servlet/view/document");
request = new MockHttpServletRequest(servletCtx);
response = new MockHttpServletResponse();
webAppCtx = new StaticWebApplicationContext();
webAppCtx.setServletContext(servletCtx);
}
public void testExcel() throws Exception {
AbstractExcelView excelView = new AbstractExcelView() {
protected void buildExcelDocument(Map model, HSSFWorkbook wb,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HSSFSheet sheet = wb.createSheet();
wb.setSheetName(0, "Test Sheet");
// test all possible permutation of row or column not existing
HSSFCell cell = getCell(sheet, 2, 4);
cell.setCellValue("Test Value");
cell = getCell(sheet, 2, 3);
setText(cell, "Test Value");
cell = getCell(sheet, 3, 4);
setText(cell, "Test Value");
cell = getCell(sheet, 2, 4);
setText(cell, "Test Value");
}
};
excelView.render(new HashMap(), request, response);
POIFSFileSystem poiFs = new POIFSFileSystem(new ByteArrayInputStream(response.getContentAsByteArray()));
HSSFWorkbook wb = new HSSFWorkbook(poiFs);
assertEquals("Test Sheet", wb.getSheetName(0));
HSSFSheet sheet = wb.getSheet("Test Sheet");
HSSFRow row = sheet.getRow(2);
HSSFCell cell = row.getCell((short) 4);
assertEquals("Test Value", cell.getStringCellValue());
}
public void testExcelWithTemplateNoLoc() throws Exception {
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
newDummyLocaleResolver("nl", "nl"));
AbstractExcelView excelView = new AbstractExcelView() {
protected void buildExcelDocument(Map model, HSSFWorkbook wb,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HSSFSheet sheet = wb.getSheet("Sheet1");
// test all possible permutation of row or column not existing
HSSFCell cell = getCell(sheet, 2, 4);
cell.setCellValue("Test Value");
cell = getCell(sheet, 2, 3);
setText(cell, "Test Value");
cell = getCell(sheet, 3, 4);
setText(cell, "Test Value");
cell = getCell(sheet, 2, 4);
setText(cell, "Test Value");
}
};
excelView.setApplicationContext(webAppCtx);
excelView.setUrl("template");
excelView.render(new HashMap(), request, response);
POIFSFileSystem poiFs = new POIFSFileSystem(new ByteArrayInputStream(response.getContentAsByteArray()));
HSSFWorkbook wb = new HSSFWorkbook(poiFs);
HSSFSheet sheet = wb.getSheet("Sheet1");
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
assertEquals("Test Template", cell.getStringCellValue());
}
public void testExcelWithTemplateAndCountryAndLanguage() throws Exception {
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
newDummyLocaleResolver("en", "US"));
AbstractExcelView excelView = new AbstractExcelView() {
protected void buildExcelDocument(Map model, HSSFWorkbook wb,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HSSFSheet sheet = wb.getSheet("Sheet1");
// test all possible permutation of row or column not existing
HSSFCell cell = getCell(sheet, 2, 4);
cell.setCellValue("Test Value");
cell = getCell(sheet, 2, 3);
setText(cell, "Test Value");
cell = getCell(sheet, 3, 4);
setText(cell, "Test Value");
cell = getCell(sheet, 2, 4);
setText(cell, "Test Value");
}
};
excelView.setApplicationContext(webAppCtx);
excelView.setUrl("template");
excelView.render(new HashMap(), request, response);
POIFSFileSystem poiFs = new POIFSFileSystem(new ByteArrayInputStream(response.getContentAsByteArray()));
HSSFWorkbook wb = new HSSFWorkbook(poiFs);
HSSFSheet sheet = wb.getSheet("Sheet1");
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
assertEquals("Test Template American English", cell.getStringCellValue());
}
public void testExcelWithTemplateAndLanguage() throws Exception {
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
newDummyLocaleResolver("de", ""));
AbstractExcelView excelView = new AbstractExcelView() {
protected void buildExcelDocument(Map model, HSSFWorkbook wb,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
HSSFSheet sheet = wb.getSheet("Sheet1");
// test all possible permutation of row or column not existing
HSSFCell cell = getCell(sheet, 2, 4);
cell.setCellValue("Test Value");
cell = getCell(sheet, 2, 3);
setText(cell, "Test Value");
cell = getCell(sheet, 3, 4);
setText(cell, "Test Value");
cell = getCell(sheet, 2, 4);
setText(cell, "Test Value");
}
};
excelView.setApplicationContext(webAppCtx);
excelView.setUrl("template");
excelView.render(new HashMap(), request, response);
POIFSFileSystem poiFs = new POIFSFileSystem(new ByteArrayInputStream(response.getContentAsByteArray()));
HSSFWorkbook wb = new HSSFWorkbook(poiFs);
HSSFSheet sheet = wb.getSheet("Sheet1");
HSSFRow row = sheet.getRow(0);
HSSFCell cell = row.getCell((short) 0);
assertEquals("Test Template auf Deutsch", cell.getStringCellValue());
}
public void testJExcel() throws Exception {
AbstractJExcelView excelView = new AbstractJExcelView() {
protected void buildExcelDocument(Map model,
WritableWorkbook wb,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
WritableSheet sheet = wb.createSheet("Test Sheet", 0);
// test all possible permutation of row or column not existing
sheet.addCell(new Label(2, 4, "Test Value"));
sheet.addCell(new Label(2, 3, "Test Value"));
sheet.addCell(new Label(3, 4, "Test Value"));
sheet.addCell(new Label(2, 4, "Test Value"));
}
};
excelView.render(new HashMap(), request, response);
Workbook wb = Workbook.getWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
assertEquals("Test Sheet", wb.getSheet(0).getName());
Sheet sheet = wb.getSheet("Test Sheet");
Cell cell = sheet.getCell(2, 4);
assertEquals("Test Value", cell.getContents());
}
public void testJExcelWithTemplateNoLoc() throws Exception {
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
newDummyLocaleResolver("nl", "nl"));
AbstractJExcelView excelView = new AbstractJExcelView() {
protected void buildExcelDocument(Map model,
WritableWorkbook wb,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
WritableSheet sheet = wb.getSheet("Sheet1");
// test all possible permutation of row or column not existing
sheet.addCell(new Label(2, 4, "Test Value"));
sheet.addCell(new Label(2, 3, "Test Value"));
sheet.addCell(new Label(3, 4, "Test Value"));
sheet.addCell(new Label(2, 4, "Test Value"));
}
};
excelView.setApplicationContext(webAppCtx);
excelView.setUrl("template");
excelView.render(new HashMap(), request, response);
Workbook wb = Workbook.getWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
Sheet sheet = wb.getSheet("Sheet1");
Cell cell = sheet.getCell(0, 0);
assertEquals("Test Template", cell.getContents());
}
public void testJExcelWithTemplateAndCountryAndLanguage() throws Exception {
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
newDummyLocaleResolver("en", "US"));
AbstractJExcelView excelView = new AbstractJExcelView() {
protected void buildExcelDocument(Map model,
WritableWorkbook wb,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
WritableSheet sheet = wb.getSheet("Sheet1");
// test all possible permutation of row or column not existing
sheet.addCell(new Label(2, 4, "Test Value"));
sheet.addCell(new Label(2, 3, "Test Value"));
sheet.addCell(new Label(3, 4, "Test Value"));
sheet.addCell(new Label(2, 4, "Test Value"));
}
};
excelView.setApplicationContext(webAppCtx);
excelView.setUrl("template");
excelView.render(new HashMap(), request, response);
Workbook wb = Workbook.getWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
Sheet sheet = wb.getSheet("Sheet1");
Cell cell = sheet.getCell(0, 0);
assertEquals("Test Template American English", cell.getContents());
}
public void testJExcelWithTemplateAndLanguage() throws Exception {
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE,
newDummyLocaleResolver("de", ""));
AbstractJExcelView excelView = new AbstractJExcelView() {
protected void buildExcelDocument(Map model,
WritableWorkbook wb,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
WritableSheet sheet = wb.getSheet("Sheet1");
// test all possible permutation of row or column not existing
sheet.addCell(new Label(2, 4, "Test Value"));
sheet.addCell(new Label(2, 3, "Test Value"));
sheet.addCell(new Label(3, 4, "Test Value"));
sheet.addCell(new Label(2, 4, "Test Value"));
}
};
excelView.setApplicationContext(webAppCtx);
excelView.setUrl("template");
excelView.render(new HashMap(), request, response);
Workbook wb = Workbook.getWorkbook(new ByteArrayInputStream(response.getContentAsByteArray()));
Sheet sheet = wb.getSheet("Sheet1");
Cell cell = sheet.getCell(0, 0);
assertEquals("Test Template auf Deutsch", cell.getContents());
}
private LocaleResolver newDummyLocaleResolver(final String lang, final String country) {
return new LocaleResolver() {
public Locale resolveLocale(HttpServletRequest request) {
return new Locale(lang, country);
}
public void setLocale(HttpServletRequest request,
HttpServletResponse response, Locale locale) {
// not supported!
}
};
}
}

View File

@@ -1,78 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.document;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
/**
* @author Alef Arendsen
* @author Juergen Hoeller
*/
public class PdfViewTests extends TestCase {
public void testPdf() throws Exception {
final String text = "this should be in the PDF";
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
AbstractPdfView pdfView = new AbstractPdfView() {
protected void buildPdfDocument(Map model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception {
document.add(new Paragraph(text));
}
};
pdfView.render(new HashMap(), request, response);
byte[] pdfContent = response.getContentAsByteArray();
assertEquals("correct response content type", "application/pdf", response.getContentType());
assertEquals("correct response content length", pdfContent.length, response.getContentLength());
// rebuild iText document for comparison
Document document = new Document(PageSize.A4);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter writer = PdfWriter.getInstance(document, baos);
writer.setViewerPreferences(PdfWriter.AllowPrinting | PdfWriter.PageLayoutSinglePage);
document.open();
document.add(new Paragraph(text));
document.close();
byte[] baosContent = baos.toByteArray();
assertEquals("correct size", pdfContent.length, baosContent.length);
int diffCount = 0;
for (int i = 0; i < pdfContent.length; i++) {
if (pdfContent[i] != baosContent[i]) {
diffCount++;
}
}
assertTrue("difference only in encryption", diffCount < 70);
}
}

View File

@@ -1,105 +0,0 @@
/*
* 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.servlet.view.freemarker;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import freemarker.cache.ClassTemplateLoader;
import freemarker.cache.MultiTemplateLoader;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import junit.framework.TestCase;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.ui.freemarker.FreeMarkerConfigurationFactoryBean;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.ui.freemarker.SpringTemplateLoader;
/**
* @author Juergen Hoeller
* @since 14.03.2004
*/
public class FreeMarkerConfigurerTests extends TestCase {
public void testTemplateLoaders() throws Exception {
FreeMarkerConfigurer fc = new FreeMarkerConfigurer();
fc.setTemplateLoaders(new TemplateLoader[] {});
fc.afterPropertiesSet();
assertTrue(fc.getConfiguration().getTemplateLoader() instanceof ClassTemplateLoader);
fc = new FreeMarkerConfigurer();
fc.setTemplateLoaders(new TemplateLoader[] {new ClassTemplateLoader()});
fc.afterPropertiesSet();
assertTrue(fc.getConfiguration().getTemplateLoader() instanceof MultiTemplateLoader);
}
public void testFreemarkerConfigurationFactoryBeanWithConfigLocation() throws TemplateException {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setConfigLocation(new FileSystemResource("myprops.properties"));
Properties props = new Properties();
props.setProperty("myprop", "/mydir");
fcfb.setFreemarkerSettings(props);
try {
fcfb.afterPropertiesSet();
fail("Should have thrown IOException");
}
catch (IOException ex) {
// expected
}
}
public void testFreeMarkerConfigurationFactoryBeanWithResourceLoaderPath() throws Exception {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setTemplateLoaderPath("file:/mydir");
fcfb.afterPropertiesSet();
Configuration cfg = (Configuration) fcfb.getObject();
assertTrue(cfg.getTemplateLoader() instanceof SpringTemplateLoader);
}
public void testFreemarkerConfigurationFactoryBeanWithNonFileResourceLoaderPath()
throws IOException, TemplateException {
FreeMarkerConfigurationFactoryBean fcfb = new FreeMarkerConfigurationFactoryBean();
fcfb.setTemplateLoaderPath("file:/mydir");
Properties settings = new Properties();
settings.setProperty("localized_lookup", "false");
fcfb.setFreemarkerSettings(settings);
fcfb.setResourceLoader(new ResourceLoader() {
public Resource getResource(String location) {
if (!("file:/mydir".equals(location) || "file:/mydir/test".equals(location))) {
throw new IllegalArgumentException(location);
}
return new ByteArrayResource("test".getBytes(), "test");
}
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
});
fcfb.afterPropertiesSet();
assertTrue(fcfb.getObject() instanceof Configuration);
Configuration fc = (Configuration) fcfb.getObject();
Template ft = fc.getTemplate("test");
assertEquals("test", FreeMarkerTemplateUtils.processTemplateIntoString(ft, new HashMap()));
}
}

View File

@@ -1,191 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.freemarker;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import junit.framework.TestCase;
import org.springframework.beans.TestBean;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.util.StringUtils;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.support.BindStatus;
import org.springframework.web.servlet.support.RequestContext;
import org.springframework.web.servlet.theme.FixedThemeResolver;
import org.springframework.web.servlet.view.DummyMacroRequestContext;
/**
* @author Darren Davison
* @author Juergen Hoeller
* @since 25.01.2005
*/
public class FreeMarkerMacroTests extends TestCase {
private static final String TEMPLATE_FILE = "test.ftl";
private StaticWebApplicationContext wac;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private FreeMarkerConfigurer fc;
public void setUp() throws Exception {
wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
//final Template expectedTemplate = new Template();
fc = new FreeMarkerConfigurer();
fc.setPreferFileSystemAccess(false);
fc.afterPropertiesSet();
wac.getDefaultListableBeanFactory().registerSingleton("freeMarkerConfigurer", fc);
wac.refresh();
request = new MockHttpServletRequest();
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, new FixedThemeResolver());
response = new MockHttpServletResponse();
}
public void testExposeSpringMacroHelpers() throws Exception {
FreeMarkerView fv = new FreeMarkerView() {
protected void processTemplate(Template template, Map model, HttpServletResponse response) {
assertTrue(model.get(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE) instanceof RequestContext);
RequestContext rc = (RequestContext) model.get(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE);
BindStatus status = rc.getBindStatus("tb.name");
assertEquals("name", status.getExpression());
assertEquals("juergen", status.getValue());
}
};
fv.setUrl(TEMPLATE_FILE);
fv.setApplicationContext(wac);
fv.setExposeSpringMacroHelpers(true);
Map model = new HashMap();
model.put("tb", new TestBean("juergen", 99));
fv.render(model, request, response);
}
public void testSpringMacroRequestContextAttributeUsed() {
final String helperTool = "wrongType";
FreeMarkerView fv = new FreeMarkerView() {
protected void processTemplate(Template template, Map model, HttpServletResponse response) {
fail();
}
};
fv.setUrl(TEMPLATE_FILE);
fv.setApplicationContext(wac);
fv.setExposeSpringMacroHelpers(true);
Map model = new HashMap();
model.put(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, helperTool);
try {
fv.render(model, request, response);
}
catch (Exception ex) {
assertTrue(ex instanceof ServletException);
assertTrue(ex.getMessage().indexOf(FreeMarkerView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE) > -1);
}
}
public void testAllMacros() throws Exception {
DummyMacroRequestContext rc = new DummyMacroRequestContext(request);
Map msgMap = new HashMap();
msgMap.put("hello", "Howdy");
msgMap.put("world", "Mundo");
rc.setMessageMap(msgMap);
Map themeMsgMap = new HashMap();
themeMsgMap.put("hello", "Howdy!");
themeMsgMap.put("world", "Mundo!");
rc.setThemeMessageMap(themeMsgMap);
rc.setContextPath("/springtest");
TestBean tb = new TestBean("Darren", 99);
tb.setSpouse(new TestBean("Fred"));
request.setAttribute("command", tb);
HashMap names = new HashMap();
names.put("Darren", "Darren Davison");
names.put("John", "John Doe");
names.put("Fred", "Fred Bloggs");
names.put("Rob&Harrop", "Rob Harrop");
Configuration config = fc.getConfiguration();
Map model = new HashMap();
model.put("command", tb);
model.put("springMacroRequestContext", rc);
model.put("msgArgs", new Object[] {"World"});
model.put("nameOptionMap", names);
model.put("options", names.values());
FreeMarkerView view = new FreeMarkerView();
view.setBeanName("myView");
view.setUrl("test.ftl");
view.setExposeSpringMacroHelpers(false);
view.setConfiguration(config);
view.render(model, request, response);
// tokenize output and ignore whitespace
String output = response.getContentAsString();
System.out.println(output);
String[] tokens = StringUtils.tokenizeToStringArray(output, "\t\n");
for (int i = 0; i < tokens.length; i++) {
if (tokens[i].equals("NAME")) assertEquals("Darren", tokens[i + 1]);
if (tokens[i].equals("AGE")) assertEquals("99", tokens[i + 1]);
if (tokens[i].equals("MESSAGE")) assertEquals("Howdy Mundo", tokens[i + 1]);
if (tokens[i].equals("DEFAULTMESSAGE")) assertEquals("hi planet", tokens[i + 1]);
if (tokens[i].equals("MESSAGEARGS")) assertEquals("Howdy[World]", tokens[i + 1]);
if (tokens[i].equals("MESSAGEARGSWITHDEFAULTMESSAGE")) assertEquals("Hi", tokens[i + 1]);
if (tokens[i].equals("THEME")) assertEquals("Howdy! Mundo!", tokens[i + 1]);
if (tokens[i].equals("DEFAULTTHEME")) assertEquals("hi! planet!", tokens[i + 1]);
if (tokens[i].equals("THEMEARGS")) assertEquals("Howdy![World]", tokens[i + 1]);
if (tokens[i].equals("THEMEARGSWITHDEFAULTMESSAGE")) assertEquals("Hi!", tokens[i + 1]);
if (tokens[i].equals("URL")) assertEquals("/springtest/aftercontext.html", tokens[i + 1]);
if (tokens[i].equals("FORM1")) assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
if (tokens[i].equals("FORM2")) assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" class=\"myCssClass\" >", tokens[i + 1]);
if (tokens[i].equals("FORM3")) assertEquals("<textarea id=\"name\" name=\"name\" >Darren</textarea>", tokens[i + 1]);
if (tokens[i].equals("FORM4")) assertEquals("<textarea id=\"name\" name=\"name\" rows=10 cols=30>Darren</textarea>", tokens[i + 1]);
//TODO verify remaining output (fix whitespace)
if (tokens[i].equals("FORM9")) assertEquals("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >", tokens[i + 1]);
if (tokens[i].equals("FORM10")) assertEquals("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
if (tokens[i].equals("FORM11")) assertEquals("<input type=\"text\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
if (tokens[i].equals("FORM12")) assertEquals("<input type=\"hidden\" id=\"name\" name=\"name\" value=\"Darren\" >", tokens[i + 1]);
if (tokens[i].equals("FORM13")) assertEquals("<input type=\"password\" id=\"name\" name=\"name\" value=\"\" >", tokens[i + 1]);
}
}
}

View File

@@ -1,174 +0,0 @@
/*
* 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.servlet.view.freemarker;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import junit.framework.TestCase;
import org.easymock.MockControl;
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.view.AbstractView;
/**
* @author Juergen Hoeller
* @since 14.03.2004
*/
public class FreeMarkerViewTests extends TestCase {
public void testNoFreemarkerConfig() {
FreeMarkerView fv = new FreeMarkerView();
MockControl wmc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
wac.getBeansOfType(FreeMarkerConfig.class, true, false);
wmc.setReturnValue(new HashMap());
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wmc.replay();
fv.setUrl("anythingButNull");
try {
fv.setApplicationContext(wac);
fail();
}
catch (ApplicationContextException ex) {
// Check there's a helpful error message
assertTrue(ex.getMessage().indexOf("FreeMarkerConfig") != -1);
}
wmc.verify();
}
public void testNoTemplateName() throws Exception {
FreeMarkerView fv = new FreeMarkerView();
try {
fv.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// Check there's a helpful error message
assertTrue(ex.getMessage().indexOf("url") != -1);
}
}
public void testValidTemplateName() throws Exception {
FreeMarkerView fv = new FreeMarkerView();
MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
MockServletContext sc = new MockServletContext();
wac.getBeansOfType(FreeMarkerConfig.class, true, false);
Map configs = new HashMap();
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setConfiguration(new TestConfiguration());
configs.put("freemarkerConfig", configurer);
wmc.setReturnValue(configs);
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wac.getServletContext();
wmc.setReturnValue(sc, 4);
wmc.replay();
fv.setUrl("templateName");
fv.setApplicationContext(wac);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.US);
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
HttpServletResponse response = new MockHttpServletResponse();
Map model = new HashMap();
model.put("myattr", "myvalue");
fv.render(model, request, response);
wmc.verify();
assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, response.getContentType());
}
public void testKeepExistingContentType() throws Exception {
FreeMarkerView fv = new FreeMarkerView();
MockControl wmc = MockControl.createNiceControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
MockServletContext sc = new MockServletContext();
wac.getBeansOfType(FreeMarkerConfig.class, true, false);
Map configs = new HashMap();
FreeMarkerConfigurer configurer = new FreeMarkerConfigurer();
configurer.setConfiguration(new TestConfiguration());
configs.put("freemarkerConfig", configurer);
wmc.setReturnValue(configs);
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wac.getServletContext();
wmc.setReturnValue(sc, 4);
wmc.replay();
fv.setUrl("templateName");
fv.setApplicationContext(wac);
MockHttpServletRequest request = new MockHttpServletRequest();
request.addPreferredLocale(Locale.US);
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
HttpServletResponse response = new MockHttpServletResponse();
response.setContentType("myContentType");
Map model = new HashMap();
model.put("myattr", "myvalue");
fv.render(model, request, response);
wmc.verify();
assertEquals("myContentType", response.getContentType());
}
private class TestConfiguration extends Configuration {
public Template getTemplate(String name, final Locale locale) throws IOException {
assertEquals("templateName", name);
return new Template(name, new StringReader("test")) {
public void process(Object model, Writer writer) throws TemplateException, IOException {
assertEquals(Locale.US, locale);
assertTrue(model instanceof Map);
Map modelMap = (Map) model;
assertEquals("myvalue", modelMap.get("myattr"));
}
};
}
}
}

View File

@@ -1,79 +0,0 @@
<#--
test template for FreeMarker macro test class
-->
<#import "spring.ftl" as spring />
NAME
${command.name}
AGE
${command.age}
MESSAGE
<@spring.message "hello"/> <@spring.message "world"/>
DEFAULTMESSAGE
<@spring.messageText "no.such.code", "hi"/> <@spring.messageText "no.such.code", "planet"/>
MESSAGEARGS
<@spring.messageArgs "hello", msgArgs/>
MESSAGEARGSWITHDEFAULTMESSAGE
<@spring.messageArgsText "no.such.code", msgArgs, "Hi"/>
THEME
<@spring.theme "hello"/> <@spring.theme "world"/>
DEFAULTTHEME
<@spring.themeText "no.such.code", "hi!"/> <@spring.themeText "no.such.code", "planet!"/>
THEMEARGS
<@spring.themeArgs "hello", msgArgs/>
THEMEARGSWITHDEFAULTMESSAGE
<@spring.themeArgsText "no.such.code", msgArgs, "Hi!"/>
URL
<@spring.url "/aftercontext.html"/>
FORM1
<@spring.formInput "command.name", ""/>
FORM2
<@spring.formInput "command.name", 'class="myCssClass"'/>
FORM3
<@spring.formTextarea "command.name", ""/>
FORM4
<@spring.formTextarea "command.name", "rows=10 cols=30"/>
FORM5
<@spring.formSingleSelect "command.name", nameOptionMap, ""/>
FORM6
<@spring.formMultiSelect "command.spouses", nameOptionMap, ""/>
FORM7
<@spring.formRadioButtons "command.name", nameOptionMap, " ", ""/>
FORM8
<@spring.formCheckboxes "command.spouses", nameOptionMap, " ", ""/>
FORM9
<@spring.formPasswordInput "command.name", ""/>
FORM10
<@spring.formHiddenInput "command.name", ""/>
FORM11
<@spring.formInput "command.name", "", "text"/>
FORM12
<@spring.formInput "command.name", "", "hidden"/>
FORM13
<@spring.formInput "command.name", "", "password"/>
FORM14
<@spring.formSingleSelect "command.name", options, ""/>

View File

@@ -1,47 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import org.springframework.context.support.StaticApplicationContext;
/**
* @author Rob Harrop
*/
public abstract class AbstractConfigurableJasperReportsViewTests extends AbstractJasperReportsViewTests {
public void testSetInvalidExporterClass() throws Exception {
try {
new ConfigurableJasperReportsView().setExporterClass(String.class);
fail("Should not be able to set invalid view class.");
}
catch (IllegalArgumentException ex) {
// success
}
}
public void testNoConfiguredExporter() throws Exception {
ConfigurableJasperReportsView view = new ConfigurableJasperReportsView();
view.setUrl(COMPILED_REPORT);
try {
view.setApplicationContext(new StaticApplicationContext());
fail("Should not be able to setup view class without an exporter class.");
}
catch (IllegalArgumentException e) {
// success
}
}
}

View File

@@ -1,114 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import junit.framework.TestCase;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.ui.jasperreports.PersonBean;
import org.springframework.ui.jasperreports.ProductBean;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public abstract class AbstractJasperReportsTests extends TestCase {
protected static final String COMPILED_REPORT = "/org/springframework/ui/jasperreports/DataSourceReport.jasper";
protected static final String UNCOMPILED_REPORT = "/org/springframework/ui/jasperreports/DataSourceReport.jrxml";
protected static final String SUB_REPORT_PARENT = "/org/springframework/ui/jasperreports/subReportParent.jrxml";
protected static boolean canCompileReport;
static {
try {
Class.forName("org.eclipse.jdt.internal.compiler.Compiler");
canCompileReport = true;
}
catch (ClassNotFoundException ex) {
canCompileReport = false;
}
}
protected MockHttpServletRequest request;
protected MockHttpServletResponse response;
public void setUp() {
request = new MockHttpServletRequest();
response = new MockHttpServletResponse();
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, new AcceptHeaderLocaleResolver());
request.addPreferredLocale(Locale.GERMAN);
}
protected Map<String, Object> getModel() {
Map model = new HashMap();
model.put("ReportTitle", "Dear Lord!");
model.put("dataSource", new JRBeanCollectionDataSource(getData()));
extendModel(model);
return model;
}
/**
* Subclasses can extend the model if they need to.
*/
protected void extendModel(Map<String, Object> model) {
}
protected List getData() {
List list = new ArrayList();
for (int x = 0; x < 10; x++) {
PersonBean bean = new PersonBean();
bean.setId(x);
bean.setName("Rob Harrop");
bean.setStreet("foo");
list.add(bean);
}
return list;
}
protected List getProductData() {
List list = new ArrayList();
for (int x = 0; x < 10; x++) {
ProductBean bean = new ProductBean();
bean.setId(x);
bean.setName("Foo Bar");
bean.setPrice(1.9f);
bean.setQuantity(1.0f);
list.add(bean);
}
return list;
}
}

View File

@@ -1,423 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.data.JRAbstractBeanDataSourceProvider;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.easymock.MockControl;
import org.junit.Ignore;
import org.springframework.context.ApplicationContextException;
import org.springframework.mock.web.MockServletContext;
import org.springframework.ui.jasperreports.PersonBean;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public abstract class AbstractJasperReportsViewTests extends AbstractJasperReportsTests {
protected AbstractJasperReportsView getView(String url) throws Exception {
AbstractJasperReportsView view = getViewImplementation();
view.setUrl(url);
StaticWebApplicationContext ac = new StaticWebApplicationContext();
ac.setServletContext(new MockServletContext());
ac.addMessage("page", Locale.GERMAN, "MeineSeite");
ac.refresh();
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, ac);
view.setApplicationContext(ac);
return view;
}
/**
* Simple test to see if compiled report succeeds.
*/
public void testCompiledReport() throws Exception {
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(getModel(), request, response);
assertTrue(response.getContentAsByteArray().length > 0);
if (view instanceof AbstractJasperReportsSingleFormatView &&
((AbstractJasperReportsSingleFormatView) view).useWriter()) {
String output = response.getContentAsString();
assertTrue("Output should contain 'MeineSeite'", output.indexOf("MeineSeite") > -1);
}
}
public void testUncompiledReport() throws Exception {
if (!canCompileReport) {
return;
}
AbstractJasperReportsView view = getView(UNCOMPILED_REPORT);
view.render(getModel(), request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithInvalidPath() throws Exception {
try {
getView("foo.jasper");
fail("Invalid path should throw ApplicationContextException");
}
catch (ApplicationContextException ex) {
// good!
}
}
public void testInvalidExtension() throws Exception {
try {
getView("foo.bar");
fail("Invalid extension should throw IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testContentType() throws Exception {
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(getModel(), request, response);
assertEquals("Response content type is incorrect", getDesiredContentType(), response.getContentType());
}
public void testWithoutDatasource() throws Exception {
Map model = getModel();
model.remove("dataSource");
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(model, request, response);
assertTrue(response.getStatus() == HttpServletResponse.SC_OK);
}
public void testWithCollection() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("reportData", getData());
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(model, request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithMultipleCollections() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("reportData", getData());
model.put("otherData", new LinkedList());
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(model, request, response);
// no clear data source found
}
public void testWithJRDataSourceProvider() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("dataSource", new MockDataSourceProvider(PersonBean.class));
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(model, request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithSpecificCollection() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("reportData", getData());
model.put("otherData", new LinkedList());
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.setReportDataKey("reportData");
view.render(model, request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithArray() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("reportData", getData().toArray());
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(model, request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithMultipleArrays() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("reportData", getData().toArray());
model.put("otherData", new String[0]);
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(model, request, response);
// no clear data source found
}
public void testWithSpecificArray() throws Exception {
Map model = getModel();
model.remove("dataSource");
model.put("reportData", getData().toArray());
model.put("otherData", new String[0]);
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.setReportDataKey("reportData");
view.render(model, request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithSubReport() throws Exception {
if (!canCompileReport) {
return;
}
Map model = getModel();
model.put("SubReportData", getProductData());
Properties subReports = new Properties();
subReports.put("ProductsSubReport", "/org/springframework/ui/jasperreports/subReportChild.jrxml");
AbstractJasperReportsView view = getView(SUB_REPORT_PARENT);
view.setReportDataKey("dataSource");
view.setSubReportUrls(subReports);
view.setSubReportDataKeys(new String[]{"SubReportData"});
view.initApplicationContext();
view.render(model, request, response);
assertTrue(response.getContentAsByteArray().length > 0);
}
public void testWithNonExistentSubReport() throws Exception {
if (!canCompileReport) {
return;
}
Map model = getModel();
model.put("SubReportData", getProductData());
Properties subReports = new Properties();
subReports.put("ProductsSubReport", "org/springframework/ui/jasperreports/subReportChildFalse.jrxml");
AbstractJasperReportsView view = getView(SUB_REPORT_PARENT);
view.setReportDataKey("dataSource");
view.setSubReportUrls(subReports);
view.setSubReportDataKeys(new String[]{"SubReportData"});
try {
view.initApplicationContext();
fail("Invalid report URL should throw ApplicationContext Exception");
}
catch (ApplicationContextException ex) {
// success
}
}
@Ignore
public void ignoreTestOverrideExporterParameters() throws Exception {
AbstractJasperReportsView view = getView(COMPILED_REPORT);
if (!(view instanceof AbstractJasperReportsSingleFormatView) || !((AbstractJasperReportsSingleFormatView) view).useWriter()) {
return;
}
String characterEncoding = "UTF-8";
String overiddenCharacterEncoding = "ASCII";
Map parameters = new HashMap();
parameters.put(JRExporterParameter.CHARACTER_ENCODING, characterEncoding);
view.setExporterParameters(parameters);
view.convertExporterParameters();
Map model = getModel();
model.put(JRExporterParameter.CHARACTER_ENCODING, overiddenCharacterEncoding);
view.render(model, this.request, this.response);
assertEquals(overiddenCharacterEncoding, this.response.getCharacterEncoding());
}
public void testSubReportWithUnspecifiedParentDataSource() throws Exception {
if (!canCompileReport) {
return;
}
Map model = getModel();
model.put("SubReportData", getProductData());
Properties subReports = new Properties();
subReports.put("ProductsSubReport", "org/springframework/ui/jasperreports/subReportChildFalse.jrxml");
AbstractJasperReportsView view = getView(SUB_REPORT_PARENT);
view.setSubReportUrls(subReports);
view.setSubReportDataKeys(new String[]{"SubReportData"});
try {
view.initApplicationContext();
fail("Unspecified reportDataKey should throw exception when subReportDataSources is specified");
}
catch (ApplicationContextException ex) {
// success
}
}
public void testContentDisposition() throws Exception {
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.render(getModel(), request, response);
assertEquals("Invalid content type", "inline", response.getHeader("Content-Disposition"));
}
public void testOverrideContentDisposition() throws Exception {
Properties headers = new Properties();
String cd = "attachment";
headers.setProperty("Content-Disposition", cd);
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.setHeaders(headers);
view.render(getModel(), request, response);
assertEquals("Invalid content type", cd, response.getHeader("Content-Disposition"));
}
public void testSetCustomHeaders() throws Exception {
Properties headers = new Properties();
String key = "foo";
String value = "bar";
headers.setProperty(key, value);
AbstractJasperReportsView view = getView(COMPILED_REPORT);
view.setHeaders(headers);
view.render(getModel(), request, response);
assertNotNull("Header not present", response.getHeader(key));
assertEquals("Invalid header value", value, response.getHeader(key));
}
public void testWithJdbcDataSource() throws Exception {
if (!canCompileReport) {
return;
}
AbstractJasperReportsView view = getView(UNCOMPILED_REPORT);
view.setJdbcDataSource(getMockJdbcDataSource());
Map model = getModel();
model.remove("dataSource");
try {
view.render(model, request, response);
fail("DataSource was not used as report DataSource");
}
catch (SQLException ex) {
// expected
}
}
public void testWithJdbcDataSourceInModel() throws Exception {
if (!canCompileReport) {
return;
}
AbstractJasperReportsView view = getView(UNCOMPILED_REPORT);
Map model = getModel();
model.remove("dataSource");
model.put("someKey", getMockJdbcDataSource());
try {
view.render(model, request, response);
fail("DataSource was not used as report DataSource");
}
catch (SQLException ex) {
// expected
}
}
public void testJRDataSourceOverridesJdbcDataSource() throws Exception {
if (!canCompileReport) {
return;
}
AbstractJasperReportsView view = getView(UNCOMPILED_REPORT);
view.setJdbcDataSource(getMockJdbcDataSource());
try {
view.render(getModel(), request, response);
}
catch (SQLException ex) {
fail("javax.sql.DataSource was used when JRDataSource should have overridden it");
}
}
private DataSource getMockJdbcDataSource() throws SQLException {
MockControl ctl = MockControl.createControl(DataSource.class);
DataSource ds = (DataSource) ctl.getMock();
ds.getConnection();
ctl.setThrowable(new SQLException());
ctl.replay();
return ds;
}
public void testWithCharacterEncoding() throws Exception {
AbstractJasperReportsView view = getView(COMPILED_REPORT);
if (!(view instanceof AbstractJasperReportsSingleFormatView) || !((AbstractJasperReportsSingleFormatView) view).useWriter()) {
return;
}
String characterEncoding = "UTF-8";
Map parameters = new HashMap();
parameters.put(JRExporterParameter.CHARACTER_ENCODING, characterEncoding);
view.setExporterParameters(parameters);
view.convertExporterParameters();
view.render(getModel(), this.request, this.response);
assertEquals(characterEncoding, this.response.getCharacterEncoding());
}
protected abstract AbstractJasperReportsView getViewImplementation();
protected abstract String getDesiredContentType();
private class MockDataSourceProvider extends JRAbstractBeanDataSourceProvider {
public MockDataSourceProvider(Class clazz) {
super(clazz);
}
public JRDataSource create(JasperReport jasperReport) throws JRException {
return new JRBeanCollectionDataSource(getData());
}
public void dispose(JRDataSource jrDataSource) throws JRException {
}
}
}

View File

@@ -1,38 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import net.sf.jasperreports.engine.export.JRHtmlExporter;
/**
* @author Rob Harrop
*/
public class ConfigurableJasperReportsViewWithStreamTests extends AbstractConfigurableJasperReportsViewTests {
protected AbstractJasperReportsView getViewImplementation() {
ConfigurableJasperReportsView view = new ConfigurableJasperReportsView();
view.setExporterClass(JRHtmlExporter.class);
view.setUseWriter(true);
view.setContentType("application/pdf");
return view;
}
protected String getDesiredContentType() {
return "application/pdf";
}
}

View File

@@ -1,37 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import net.sf.jasperreports.engine.export.JRPdfExporter;
/**
* @author Rob Harrop
*/
public class ConfigurableJasperReportsViewWithWriterTests extends AbstractConfigurableJasperReportsViewTests {
protected AbstractJasperReportsView getViewImplementation() {
ConfigurableJasperReportsView view = new ConfigurableJasperReportsView();
view.setExporterClass(JRPdfExporter.class);
view.setUseWriter(false);
view.setContentType("text/html");
return view;
}
protected String getDesiredContentType() {
return "text/html";
}
}

View File

@@ -1,161 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author Rob Harrop
*/
public class ExporterParameterTests extends AbstractJasperReportsTests {
public void testParameterParsing() throws Exception {
Map params = new HashMap();
params.put("net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI", "/foo/bar");
AbstractJasperReportsView view = new AbstractJasperReportsView() {
protected void renderReport(JasperPrint filledReport, Map model, HttpServletResponse response)
throws Exception {
assertEquals("Invalid number of exporter parameters", 1, getConvertedExporterParameters().size());
JRExporterParameter key = JRHtmlExporterParameter.IMAGES_URI;
Object value = getConvertedExporterParameters().get(key);
assertNotNull("Value not mapped to correct key", value);
assertEquals("Incorrect value for parameter", "/foo/bar", value);
}
/**
* Merges the configured {@link net.sf.jasperreports.engine.JRExporterParameter JRExporterParameters} with any specified
* in the supplied model data. {@link net.sf.jasperreports.engine.JRExporterParameter JRExporterParameters} in the model
* override those specified in the configuration.
* @see #setExporterParameters(java.util.Map)
*/
protected Map mergeExporterParameters(Map model) {
Map mergedParameters = new HashMap(getConvertedExporterParameters());
for (Iterator iterator = model.keySet().iterator(); iterator.hasNext();) {
Object key = iterator.next();
if (key instanceof JRExporterParameter) {
Object value = model.get(key);
if (value instanceof String) {
mergedParameters.put(key, value);
}
else {
logger.warn("Ignoring exporter parameter [" + key + "]. Value is not a String.");
}
}
}
return mergedParameters;
}
};
view.setExporterParameters(params);
setViewProperties(view);
view.render(getModel(), request, response);
}
public void testInvalidClass() throws Exception {
Map params = new HashMap();
params.put("foo.net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI", "/foo");
AbstractJasperReportsView view = new JasperReportsHtmlView();
setViewProperties(view);
try {
view.setExporterParameters(params);
view.convertExporterParameters();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testInvalidField() {
Map params = new HashMap();
params.put("net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI_FOO", "/foo");
AbstractJasperReportsView view = new JasperReportsHtmlView();
setViewProperties(view);
try {
view.setExporterParameters(params);
view.convertExporterParameters();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testInvalidType() {
Map params = new HashMap();
params.put("java.lang.Boolean.TRUE", "/foo");
AbstractJasperReportsView view = new JasperReportsHtmlView();
setViewProperties(view);
try {
view.setExporterParameters(params);
view.convertExporterParameters();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// expected
}
}
public void testTypeConversion() {
Map params = new HashMap();
params.put("net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN", "true");
AbstractJasperReportsView view = new JasperReportsHtmlView();
setViewProperties(view);
view.setExporterParameters(params);
view.convertExporterParameters();
Object value = view.getConvertedExporterParameters().get(JRHtmlExporterParameter.IS_USING_IMAGES_TO_ALIGN);
assertEquals(Boolean.TRUE, value);
}
private void setViewProperties(AbstractJasperReportsView view) {
view.setUrl("/org/springframework/ui/jasperreports/DataSourceReport.jasper");
StaticWebApplicationContext ac = new StaticWebApplicationContext();
ac.setServletContext(new MockServletContext());
ac.addMessage("page", Locale.GERMAN, "MeineSeite");
ac.refresh();
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, ac);
view.setApplicationContext(ac);
}
}

View File

@@ -1,92 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.jasperreports;
import java.util.Locale;
import junit.framework.TestCase;
import org.springframework.context.support.StaticApplicationContext;
import org.springframework.web.servlet.view.velocity.VelocityView;
/**
* @author Rob Harrop
*/
public class JasperReportViewResolverTests extends TestCase {
public void testResolveView() throws Exception {
StaticApplicationContext ctx = new StaticApplicationContext();
String prefix = "org/springframework/ui/jasperreports/";
String suffix = ".jasper";
String viewName = "DataSourceReport";
JasperReportsViewResolver viewResolver = new JasperReportsViewResolver();
viewResolver.setViewClass(JasperReportsHtmlView.class);
viewResolver.setPrefix(prefix);
viewResolver.setSuffix(suffix);
viewResolver.setApplicationContext(ctx);
AbstractJasperReportsView view =
(AbstractJasperReportsView) viewResolver.resolveViewName(viewName, Locale.ENGLISH);
assertNotNull("View should not be null", view);
assertEquals("Incorrect URL", prefix + viewName + suffix, view.getUrl());
}
public void testSetIncorrectViewClass() {
try {
new JasperReportsViewResolver().setViewClass(VelocityView.class);
fail("Should not be able to set view class to a class that does not extend AbstractJasperReportsView");
}
catch (IllegalArgumentException ex) {
// success
}
}
public void testWithViewNamesAndEndsWithPattern() throws Exception {
doViewNamesTest(new String[]{"DataSource*"});
}
public void testWithViewNamesAndStartsWithPattern() throws Exception {
doViewNamesTest(new String[]{"*Report"});
}
public void testWithViewNamesAndStatic() throws Exception {
doViewNamesTest(new String[]{"DataSourceReport"});
}
private void doViewNamesTest(String[] viewNames) throws Exception {
StaticApplicationContext ctx = new StaticApplicationContext();
String prefix = "org/springframework/ui/jasperreports/";
String suffix = ".jasper";
String viewName = "DataSourceReport";
JasperReportsViewResolver viewResolver = new JasperReportsViewResolver();
viewResolver.setViewClass(JasperReportsHtmlView.class);
viewResolver.setPrefix(prefix);
viewResolver.setSuffix(suffix);
viewResolver.setViewNames(viewNames);
viewResolver.setApplicationContext(ctx);
AbstractJasperReportsView view =
(AbstractJasperReportsView) viewResolver.resolveViewName(viewName, Locale.ENGLISH);
assertNotNull("View should not be null", view);
assertEquals("Incorrect URL", prefix + viewName + suffix, view.getUrl());
assertNull(viewResolver.resolveViewName("foo", Locale.ENGLISH));
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.jasperreports;
/**
* @author Rob Harrop
*/
public class JasperReportsCsvViewTests extends AbstractJasperReportsViewTests {
protected AbstractJasperReportsView getViewImplementation() {
return new JasperReportsCsvView();
}
protected String getDesiredContentType() {
return "text/csv";
}
}

View File

@@ -1,57 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import net.sf.jasperreports.engine.export.JRHtmlExporterParameter;
import org.springframework.beans.factory.support.BeanDefinitionReader;
import org.springframework.beans.factory.support.PropertiesBeanDefinitionReader;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
/**
* @author Rob Harrop
*/
public class JasperReportsHtmlViewTests extends AbstractJasperReportsViewTests {
protected AbstractJasperReportsView getViewImplementation() {
return new JasperReportsHtmlView();
}
protected String getDesiredContentType() {
return "text/html";
}
public void testConfigureExporterParametersWithEncodingFromPropertiesFile() throws Exception {
GenericWebApplicationContext ac = new GenericWebApplicationContext();
ac.setServletContext(new MockServletContext());
BeanDefinitionReader reader = new PropertiesBeanDefinitionReader(ac);
reader.loadBeanDefinitions(new ClassPathResource("view.properties", getClass()));
ac.refresh();
AbstractJasperReportsView view = (AbstractJasperReportsView) ac.getBean("report");
String encoding = (String) view.getConvertedExporterParameters().get(JRHtmlExporterParameter.CHARACTER_ENCODING);
assertEquals("UTF-8", encoding);
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, ac);
view.render(getModel(), request, response);
assertEquals("Response content type is incorrect", "text/html;charset=UTF-8", response.getContentType());
}
}

View File

@@ -1,129 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperPrint;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class JasperReportsMultiFormatViewTests extends AbstractJasperReportsViewTests {
protected void extendModel(Map<String, Object> model) {
model.put(getDiscriminatorKey(), "csv");
}
public void testSimpleHtmlRender() throws Exception {
if (!canCompileReport) {
return;
}
AbstractJasperReportsView view = getView(UNCOMPILED_REPORT);
Map<String, Object> model = getBaseModel();
model.put(getDiscriminatorKey(), "html");
view.render(model, request, response);
assertEquals("Invalid content type", "text/html", response.getContentType());
}
public void testOverrideContentDisposition() throws Exception {
if (!canCompileReport) {
return;
}
AbstractJasperReportsView view = getView(UNCOMPILED_REPORT);
Map<String, Object> model = getBaseModel();
model.put(getDiscriminatorKey(), "csv");
String headerValue = "inline; filename=foo.txt";
Properties mappings = new Properties();
mappings.put("csv", headerValue);
((JasperReportsMultiFormatView) view).setContentDispositionMappings(mappings);
view.render(model, request, response);
assertEquals("Invalid Content-Disposition header value", headerValue,
response.getHeader("Content-Disposition"));
}
public void testExporterParametersAreCarriedAcross() throws Exception {
if (!canCompileReport) {
return;
}
JasperReportsMultiFormatView view = (JasperReportsMultiFormatView) getView(UNCOMPILED_REPORT);
Map<String, Class> mappings = new HashMap<String, Class>();
mappings.put("test", ExporterParameterTestView.class);
Map<String, String> exporterParameters = new HashMap<String, String>();
// test view class performs the assertions - robh
exporterParameters.put(ExporterParameterTestView.TEST_PARAM, "foo");
view.setExporterParameters(exporterParameters);
view.setFormatMappings(mappings);
view.initApplicationContext();
Map<String, Object> model = getBaseModel();
model.put(getDiscriminatorKey(), "test");
view.render(model, request, response);
}
protected String getDiscriminatorKey() {
return "format";
}
protected AbstractJasperReportsView getViewImplementation() {
return new JasperReportsMultiFormatView();
}
protected String getDesiredContentType() {
return "text/csv";
}
private Map<String, Object> getBaseModel() {
Map<String, Object> model = new HashMap<String, Object>();
model.put("ReportTitle", "Foo");
model.put("dataSource", getData());
return model;
}
public static class ExporterParameterTestView extends AbstractJasperReportsView {
public static final String TEST_PARAM = "net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI";
protected void renderReport(JasperPrint filledReport, Map parameters, HttpServletResponse response) {
assertNotNull("Exporter parameters are null", getExporterParameters());
assertEquals("Incorrect number of exporter parameters", 1, getExporterParameters().size());
}
}
}

View File

@@ -1,47 +0,0 @@
/*
* 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.servlet.view.jasperreports;
import java.util.HashMap;
import java.util.Map;
/**
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class JasperReportsMultiFormatViewWithCustomMappingsTests extends JasperReportsMultiFormatViewTests {
protected AbstractJasperReportsView getViewImplementation() {
JasperReportsMultiFormatView view = new JasperReportsMultiFormatView();
view.setFormatKey("fmt");
Map<String, Class> mappings = new HashMap<String, Class>();
mappings.put("csv", JasperReportsCsvView.class);
mappings.put("comma-separated", JasperReportsCsvView.class);
mappings.put("html", JasperReportsHtmlView.class);
view.setFormatMappings(mappings);
return view;
}
protected String getDiscriminatorKey() {
return "fmt";
}
protected void extendModel(Map<String, Object> model) {
model.put(getDiscriminatorKey(), "comma-separated");
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.jasperreports;
/**
* @author Rob Harrop
*/
public class JasperReportsPdfViewTests extends AbstractJasperReportsViewTests {
protected AbstractJasperReportsView getViewImplementation() {
return new JasperReportsPdfView();
}
protected String getDesiredContentType() {
return "application/pdf";
}
}

View File

@@ -1,32 +0,0 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.jasperreports;
/**
* @author Rob Harrop
*/
public class JasperReportsXlsViewTests extends AbstractJasperReportsViewTests {
protected AbstractJasperReportsView getViewImplementation() {
return new JasperReportsXlsView();
}
protected String getDesiredContentType() {
return "application/vnd.ms-excel";
}
}

View File

@@ -1,4 +0,0 @@
report.(class)=org.springframework.web.servlet.view.jasperreports.JasperReportsHtmlView
report.url=/org/springframework/ui/jasperreports/DataSourceReport.jasper
report.exporterParameters[net.sf.jasperreports.engine.export.JRHtmlExporterParameter.CHARACTER_ENCODING]=UTF-8
report.exporterParameters[net.sf.jasperreports.engine.JRExporterParameter.PAGE_INDEX]=0

View File

@@ -1,14 +0,0 @@
debug.Parent.(class)=org.springframework.web.servlet.view.InternalResourceView
debug.Parent.(abstract)=true
debugView.(parent)=debug.Parent
debugView.url=jsp/debug/debug.jsp
debugView.attributesCSV=foo=[bar],\
postcode=[SE10 9JY]
# The following class name as a trailing space.
testParent.class=org.springframework.web.servlet.view.ResourceBundleViewResolverTests$TestView
testParent.(abstract)=true
test.location=WEB-INF/test
test.(class)=org.springframework.web.servlet.view.ResourceBundleViewResolverTests$TestView

View File

@@ -1 +0,0 @@
# This empty file is mandatory to have the test passed on french systems.

View File

@@ -1,3 +0,0 @@
debugView.(class)= org.springframework.web.servlet.view.InternalResourceView
debugView.url=jsp/debug/deboug.jsp
debugView.contentType=text/xml;charset=ISO-8859-1

View File

@@ -1,54 +0,0 @@
/*
* 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.servlet.view.velocity;
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
/**
* @author Juergen Hoeller
* @since 09.10.2004
*/
public class TestVelocityEngine extends VelocityEngine {
private final Map templates = new HashMap();
public TestVelocityEngine() {
}
public TestVelocityEngine(String expectedName, Template template) {
addTemplate(expectedName, template);
}
public void addTemplate(String expectedName, Template template) {
this.templates.put(expectedName, template);
}
public Template getTemplate(String name) {
Template template = (Template) this.templates.get(name);
if (template == null) {
throw new IllegalStateException("No template registered for name [" + name + "]");
}
return template;
}
}

View File

@@ -1,153 +0,0 @@
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.servlet.view.velocity;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;
import junit.framework.TestCase;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.DescriptiveResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.UrlResource;
import org.springframework.ui.velocity.VelocityEngineFactoryBean;
import org.springframework.ui.velocity.VelocityEngineUtils;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class VelocityConfigurerTests extends TestCase {
public void testVelocityEngineFactoryBeanWithConfigLocation() throws VelocityException {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
vefb.setConfigLocation(new FileSystemResource("myprops.properties"));
Properties props = new Properties();
props.setProperty("myprop", "/mydir");
vefb.setVelocityProperties(props);
try {
vefb.afterPropertiesSet();
fail("Should have thrown IOException");
}
catch (IOException ex) {
// expected
}
}
public void testVelocityEngineFactoryBeanWithVelocityProperties() throws VelocityException, IOException {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
Properties props = new Properties();
props.setProperty("myprop", "/mydir");
vefb.setVelocityProperties(props);
Object value = new Object();
Map map = new HashMap();
map.put("myentry", value);
vefb.setVelocityPropertiesMap(map);
vefb.afterPropertiesSet();
assertTrue(vefb.getObject() instanceof VelocityEngine);
VelocityEngine ve = (VelocityEngine) vefb.getObject();
assertEquals("/mydir", ve.getProperty("myprop"));
assertEquals(value, ve.getProperty("myentry"));
}
public void testVelocityEngineFactoryBeanWithResourceLoaderPath() throws IOException, VelocityException {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
vefb.setResourceLoaderPath("file:/mydir");
vefb.afterPropertiesSet();
assertTrue(vefb.getObject() instanceof VelocityEngine);
VelocityEngine ve = (VelocityEngine) vefb.getObject();
assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
public void testVelocityEngineFactoryBeanWithNonFileResourceLoaderPath() throws Exception {
VelocityEngineFactoryBean vefb = new VelocityEngineFactoryBean();
vefb.setResourceLoaderPath("file:/mydir");
vefb.setResourceLoader(new ResourceLoader() {
public Resource getResource(String location) {
if (location.equals("file:/mydir") || location.equals("file:/mydir/test")) {
return new ByteArrayResource("test".getBytes(), "test");
}
try {
return new UrlResource(location);
}
catch (MalformedURLException ex) {
throw new IllegalArgumentException(ex.toString());
}
}
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
});
vefb.afterPropertiesSet();
assertTrue(vefb.getObject() instanceof VelocityEngine);
VelocityEngine ve = (VelocityEngine) vefb.getObject();
assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap()));
}
public void testVelocityConfigurer() throws IOException, VelocityException {
VelocityConfigurer vc = new VelocityConfigurer();
vc.setResourceLoaderPath("file:/mydir");
vc.afterPropertiesSet();
assertTrue(vc.createVelocityEngine() instanceof VelocityEngine);
VelocityEngine ve = vc.createVelocityEngine();
assertEquals(new File("/mydir").getAbsolutePath(), ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
public void testVelocityConfigurerWithCsvPath() throws IOException, VelocityException {
VelocityConfigurer vc = new VelocityConfigurer();
vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
vc.afterPropertiesSet();
assertTrue(vc.createVelocityEngine() instanceof VelocityEngine);
VelocityEngine ve = vc.createVelocityEngine();
Vector paths = new Vector();
paths.add(new File("/mydir").getAbsolutePath());
paths.add(new File("/yourdir").getAbsolutePath());
assertEquals(paths, ve.getProperty(VelocityEngine.FILE_RESOURCE_LOADER_PATH));
}
public void testVelocityConfigurerWithCsvPathAndNonFileAccess() throws IOException, VelocityException {
VelocityConfigurer vc = new VelocityConfigurer();
vc.setResourceLoaderPath("file:/mydir,file:/yourdir");
vc.setResourceLoader(new ResourceLoader() {
public Resource getResource(String location) {
if ("file:/yourdir/test".equals(location)) {
return new DescriptiveResource("");
}
return new ByteArrayResource("test".getBytes(), "test");
}
public ClassLoader getClassLoader() {
return getClass().getClassLoader();
}
});
vc.setPreferFileSystemAccess(false);
vc.afterPropertiesSet();
assertTrue(vc.createVelocityEngine() instanceof VelocityEngine);
VelocityEngine ve = vc.createVelocityEngine();
assertEquals("test", VelocityEngineUtils.mergeTemplateIntoString(ve, "test", new HashMap()));
}
}

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