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

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

View File

@@ -0,0 +1,64 @@
/*
* Copyright 2002-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.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

@@ -458,4 +458,4 @@ public class ComplexWebApplicationContext extends StaticWebApplicationContext {
}
}
}
}

View File

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

View File

@@ -0,0 +1,171 @@
/*
* 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

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

@@ -0,0 +1,95 @@
/*
* 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

@@ -0,0 +1,284 @@
/*
* 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

@@ -0,0 +1,114 @@
/*
* 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

@@ -0,0 +1,146 @@
/*
* 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

@@ -0,0 +1,237 @@
/*
* 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

@@ -0,0 +1,235 @@
/*
* 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

@@ -0,0 +1,28 @@
/*
* 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

@@ -0,0 +1,181 @@
/*
* 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

@@ -0,0 +1,331 @@
/*
* 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

@@ -0,0 +1,78 @@
/*
* 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

@@ -0,0 +1,105 @@
/*
* 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

@@ -0,0 +1,191 @@
/*
* 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

@@ -0,0 +1,174 @@
/*
* Copyright 2002-2008 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.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

@@ -0,0 +1,79 @@
<#--
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

@@ -0,0 +1,47 @@
/*
* 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

@@ -0,0 +1,114 @@
/*
* 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

@@ -0,0 +1,423 @@
/*
* 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

@@ -0,0 +1,38 @@
/*
* 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

@@ -0,0 +1,37 @@
/*
* 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

@@ -0,0 +1,161 @@
/*
* 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

@@ -0,0 +1,92 @@
/*
* 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

@@ -0,0 +1,32 @@
/*
* 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

@@ -0,0 +1,57 @@
/*
* 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

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

@@ -0,0 +1,47 @@
/*
* 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

@@ -0,0 +1,32 @@
/*
* 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

@@ -0,0 +1,32 @@
/*
* 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

@@ -0,0 +1,4 @@
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

@@ -0,0 +1,14 @@
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

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

View File

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

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2002-2006 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.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

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

View File

@@ -0,0 +1,184 @@
/*
* 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.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import junit.framework.TestCase;
import org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
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 18.06.2004
*/
public class VelocityMacroTests extends TestCase {
private static final String TEMPLATE_FILE = "test.vm";
private StaticWebApplicationContext wac;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
public void setUp() throws Exception {
wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(TEMPLATE_FILE, expectedTemplate);
}
};
wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc);
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 {
VelocityView vv = new VelocityView() {
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
assertTrue(context.get(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE) instanceof RequestContext);
RequestContext rc = (RequestContext) context.get(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE);
BindStatus status = rc.getBindStatus("tb.name");
assertEquals("name", status.getExpression());
assertEquals("juergen", status.getValue());
}
};
vv.setUrl(TEMPLATE_FILE);
vv.setApplicationContext(wac);
vv.setExposeSpringMacroHelpers(true);
Map model = new HashMap();
model.put("tb", new TestBean("juergen", 99));
vv.render(model, request, response);
}
public void testSpringMacroRequestContextAttributeUsed() {
final String helperTool = "wrongType";
VelocityView vv = new VelocityView() {
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
fail();
}
};
vv.setUrl(TEMPLATE_FILE);
vv.setApplicationContext(wac);
vv.setExposeSpringMacroHelpers(true);
Map model = new HashMap();
model.put(VelocityView.SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE, helperTool);
try {
vv.render(model, request, response);
}
catch (Exception ex) {
assertTrue(ex instanceof ServletException);
assertTrue(ex.getMessage().indexOf(VelocityView.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);
request.setAttribute("command", tb);
HashMap names = new HashMap();
names.put("Darren", "Darren Davison");
names.put("John", "John Doe");
names.put("Fred", "Fred Bloggs");
VelocityConfigurer vc = new VelocityConfigurer();
vc.setPreferFileSystemAccess(false);
VelocityEngine ve = vc.createVelocityEngine();
Map model = new HashMap();
model.put("command", tb);
model.put("springMacroRequestContext", rc);
model.put("nameOptionMap", names);
VelocityView view = new VelocityView();
view.setBeanName("myView");
view.setUrl("org/springframework/web/servlet/view/velocity/test.vm");
view.setEncoding("UTF-8");
view.setExposeSpringMacroHelpers(false);
view.setVelocityEngine(ve);
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("THEME")) assertEquals("Howdy! Mundo!", tokens[i + 1]);
if (tokens[i].equals("DEFAULTTHEME")) assertEquals("hi! planet!", 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]);
}
}
}

View File

@@ -0,0 +1,498 @@
/*
* 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.velocity;
import java.io.IOException;
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 org.apache.velocity.Template;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.tools.generic.DateTool;
import org.apache.velocity.tools.generic.MathTool;
import org.apache.velocity.tools.generic.NumberTool;
import org.apache.velocity.tools.view.context.ChainedContext;
import org.apache.velocity.tools.view.tools.LinkTool;
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.context.support.StaticWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.view.AbstractView;
import org.springframework.web.servlet.view.InternalResourceView;
import org.springframework.web.servlet.view.RedirectView;
/**
* @author Rod Johnson
* @author Juergen Hoeller
*/
public class VelocityViewTests extends TestCase {
public void testNoVelocityConfig() throws Exception {
VelocityView vv = new VelocityView();
MockControl wmc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
wac.getBeansOfType(VelocityConfig.class, true, false);
wmc.setReturnValue(new HashMap());
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wmc.replay();
vv.setUrl("anythingButNull");
try {
vv.setApplicationContext(wac);
fail();
}
catch (ApplicationContextException ex) {
// Check there's a helpful error message
assertTrue(ex.getMessage().indexOf("VelocityConfig") != -1);
}
wmc.verify();
}
public void testNoTemplateName() throws Exception {
VelocityView vv = new VelocityView();
try {
vv.afterPropertiesSet();
fail("Should have thrown IllegalArgumentException");
}
catch (IllegalArgumentException ex) {
// Check there's a helpful error message
assertTrue(ex.getMessage().indexOf("url") != -1);
}
}
public void testCannotResolveTemplateNameResourceNotFoundException() throws Exception {
testCannotResolveTemplateName(new ResourceNotFoundException(""));
}
public void testCannotResolveTemplateNameParseErrorException() throws Exception {
testCannotResolveTemplateName(new ParseErrorException(""));
}
public void testCannotResolveTemplateNameNonspecificException() throws Exception {
testCannotResolveTemplateName(new Exception(""));
}
/**
* Check for failure to lookup a template for a range of reasons.
*/
private void testCannotResolveTemplateName(final Exception templateLookupException) throws Exception {
final String templateName = "test.vm";
MockControl wmc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
wac.getParentBeanFactory();
wmc.setReturnValue(null);
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new VelocityEngine() {
public Template getTemplate(String tn)
throws ResourceNotFoundException, ParseErrorException, Exception {
assertEquals(tn, templateName);
throw templateLookupException;
}
};
}
};
wac.getBeansOfType(VelocityConfig.class, true, false);
Map configurers = new HashMap();
configurers.put("velocityConfigurer", vc);
wmc.setReturnValue(configurers);
wmc.replay();
VelocityView vv = new VelocityView();
//vv.setExposeDateFormatter(false);
//vv.setExposeCurrencyFormatter(false);
vv.setUrl(templateName);
try {
vv.setApplicationContext(wac);
fail();
}
catch (ApplicationContextException ex) {
assertEquals(ex.getCause(), templateLookupException);
}
wmc.verify();
}
public void testMergeTemplateSucceeds() throws Exception {
testValidTemplateName(null);
}
public void testMergeTemplateFailureWithIOException() throws Exception {
testValidTemplateName(new IOException());
}
public void testMergeTemplateFailureWithParseErrorException() throws Exception {
testValidTemplateName(new ParseErrorException(""));
}
public void testMergeTemplateFailureWithUnspecifiedException() throws Exception {
testValidTemplateName(new Exception(""));
}
/**
* @param mergeTemplateFailureException may be null in which case mergeTemplate override will succeed.
* If it's non null it will be checked
*/
private void testValidTemplateName(final Exception mergeTemplateFailureException) throws Exception {
Map model = new HashMap();
model.put("foo", "bar");
final String templateName = "test.vm";
MockControl wmc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
MockServletContext sc = new MockServletContext();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
wac.getBeansOfType(VelocityConfig.class, true, false);
Map configurers = new HashMap();
configurers.put("velocityConfigurer", vc);
wmc.setReturnValue(configurers);
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wac.getServletContext();
wmc.setReturnValue(sc, 4);
wmc.replay();
HttpServletRequest request = new MockHttpServletRequest();
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
VelocityView vv = new VelocityView() {
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception {
assertTrue(template == expectedTemplate);
assertTrue(context.getKeys().length >= 1);
assertTrue(context.get("foo").equals("bar"));
assertTrue(response == expectedResponse);
if (mergeTemplateFailureException != null) {
throw mergeTemplateFailureException;
}
}
};
vv.setUrl(templateName);
vv.setApplicationContext(wac);
try {
vv.render(model, request, expectedResponse);
if (mergeTemplateFailureException != null) {
fail();
}
}
catch (Exception ex) {
assertNotNull(mergeTemplateFailureException);
assertEquals(ex, mergeTemplateFailureException);
}
wmc.verify();
}
public void testKeepExistingContentType() throws Exception {
final String templateName = "test.vm";
MockControl wmc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
MockServletContext sc = new MockServletContext();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
wac.getBeansOfType(VelocityConfig.class, true, false);
Map configurers = new HashMap();
configurers.put("velocityConfigurer", vc);
wmc.setReturnValue(configurers);
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wac.getServletContext();
wmc.setReturnValue(sc, 4);
wmc.replay();
HttpServletRequest request = new MockHttpServletRequest();
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
expectedResponse.setContentType("myContentType");
VelocityView vv = new VelocityView() {
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) {
assertTrue(template == expectedTemplate);
assertTrue(response == expectedResponse);
}
protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
model.put("myHelper", "myValue");
}
};
vv.setUrl(templateName);
vv.setApplicationContext(wac);
vv.render(new HashMap(), request, expectedResponse);
wmc.verify();
assertEquals("myContentType", expectedResponse.getContentType());
}
public void testExposeHelpers() throws Exception {
final String templateName = "test.vm";
MockControl wmc = MockControl.createControl(WebApplicationContext.class);
WebApplicationContext wac = (WebApplicationContext) wmc.getMock();
wac.getParentBeanFactory();
wmc.setReturnValue(null);
wac.getServletContext();
wmc.setReturnValue(new MockServletContext());
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
wac.getBeansOfType(VelocityConfig.class, true, false);
Map configurers = new HashMap();
configurers.put("velocityConfigurer", vc);
wmc.setReturnValue(configurers);
wmc.replay();
// let it ask for locale
MockControl reqControl = MockControl.createControl(HttpServletRequest.class);
HttpServletRequest req = (HttpServletRequest) reqControl.getMock();
req.getAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE);
reqControl.setReturnValue(new AcceptHeaderLocaleResolver());
req.getLocale();
reqControl.setReturnValue(Locale.CANADA);
reqControl.replay();
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
VelocityView vv = new VelocityView() {
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception {
assertTrue(template == expectedTemplate);
assertTrue(response == expectedResponse);
assertEquals("myValue", context.get("myHelper"));
assertTrue(context.get("math") instanceof MathTool);
assertTrue(context.get("dateTool") instanceof DateTool);
DateTool dateTool = (DateTool) context.get("dateTool");
assertTrue(dateTool.getLocale().equals(Locale.CANADA));
assertTrue(context.get("numberTool") instanceof NumberTool);
NumberTool numberTool = (NumberTool) context.get("numberTool");
assertTrue(numberTool.getLocale().equals(Locale.CANADA));
}
protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
model.put("myHelper", "myValue");
}
};
vv.setUrl(templateName);
vv.setApplicationContext(wac);
Map<String, Class> toolAttributes = new HashMap<String, Class>();
toolAttributes.put("math", MathTool.class);
vv.setToolAttributes(toolAttributes);
vv.setDateToolAttribute("dateTool");
vv.setNumberToolAttribute("numberTool");
vv.setExposeSpringMacroHelpers(false);
vv.render(new HashMap(), req, expectedResponse);
wmc.verify();
reqControl.verify();
assertEquals(AbstractView.DEFAULT_CONTENT_TYPE, expectedResponse.getContentType());
}
public void testVelocityToolboxView() throws Exception {
final String templateName = "test.vm";
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.setServletContext(new MockServletContext());
final Template expectedTemplate = new Template();
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine(templateName, expectedTemplate);
}
};
wac.getDefaultListableBeanFactory().registerSingleton("velocityConfigurer", vc);
final HttpServletRequest expectedRequest = new MockHttpServletRequest();
final HttpServletResponse expectedResponse = new MockHttpServletResponse();
VelocityToolboxView vv = new VelocityToolboxView() {
protected void mergeTemplate(Template template, Context context, HttpServletResponse response) throws Exception {
assertTrue(template == expectedTemplate);
assertTrue(response == expectedResponse);
assertTrue(context instanceof ChainedContext);
assertEquals("this is foo.", context.get("foo"));
assertTrue(context.get("map") instanceof HashMap);
assertTrue(context.get("date") instanceof DateTool);
assertTrue(context.get("math") instanceof MathTool);
assertTrue(context.get("link") instanceof LinkTool);
LinkTool linkTool = (LinkTool) context.get("link");
assertNotNull(linkTool.getContextURL());
assertTrue(context.get("link2") instanceof LinkTool);
LinkTool linkTool2 = (LinkTool) context.get("link2");
assertNotNull(linkTool2.getContextURL());
}
};
vv.setUrl(templateName);
vv.setApplicationContext(wac);
Map<String, Class> toolAttributes = new HashMap<String, Class>();
toolAttributes.put("math", MathTool.class);
toolAttributes.put("link2", LinkTool.class);
vv.setToolAttributes(toolAttributes);
vv.setToolboxConfigLocation("org/springframework/web/servlet/view/velocity/toolbox.xml");
vv.setExposeSpringMacroHelpers(false);
vv.render(new HashMap(), expectedRequest, expectedResponse);
}
public void testVelocityViewResolver() throws Exception {
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine("prefix_test_suffix", new Template());
}
};
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.getBeanFactory().registerSingleton("configurer", vc);
VelocityViewResolver vr = new VelocityViewResolver();
vr.setPrefix("prefix_");
vr.setSuffix("_suffix");
vr.setApplicationContext(wac);
View view = vr.resolveViewName("test", Locale.CANADA);
assertEquals("Correct view class", VelocityView.class, view.getClass());
assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
view = vr.resolveViewName("redirect:myUrl", Locale.getDefault());
assertEquals("Correct view class", RedirectView.class, view.getClass());
assertEquals("Correct URL", "myUrl", ((RedirectView) view).getUrl());
view = vr.resolveViewName("forward:myUrl", Locale.getDefault());
assertEquals("Correct view class", InternalResourceView.class, view.getClass());
assertEquals("Correct URL", "myUrl", ((InternalResourceView) view).getUrl());
}
public void testVelocityViewResolverWithToolbox() throws Exception {
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
return new TestVelocityEngine("prefix_test_suffix", new Template());
}
};
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.getBeanFactory().registerSingleton("configurer", vc);
String toolbox = "org/springframework/web/servlet/view/velocity/toolbox.xml";
VelocityViewResolver vr = new VelocityViewResolver();
vr.setPrefix("prefix_");
vr.setSuffix("_suffix");
vr.setToolboxConfigLocation(toolbox);
vr.setApplicationContext(wac);
View view = vr.resolveViewName("test", Locale.CANADA);
assertEquals("Correct view class", VelocityToolboxView.class, view.getClass());
assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
assertEquals("Correct toolbox", toolbox, ((VelocityToolboxView) view).getToolboxConfigLocation());
}
public void testVelocityViewResolverWithToolboxSubclass() throws Exception {
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
TestVelocityEngine ve = new TestVelocityEngine();
ve.addTemplate("prefix_test_suffix", new Template());
ve.addTemplate(VelocityLayoutView.DEFAULT_LAYOUT_URL, new Template());
return ve;
}
};
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.getBeanFactory().registerSingleton("configurer", vc);
String toolbox = "org/springframework/web/servlet/view/velocity/toolbox.xml";
VelocityViewResolver vr = new VelocityViewResolver();
vr.setViewClass(VelocityLayoutView.class);
vr.setPrefix("prefix_");
vr.setSuffix("_suffix");
vr.setToolboxConfigLocation(toolbox);
vr.setApplicationContext(wac);
View view = vr.resolveViewName("test", Locale.CANADA);
assertEquals("Correct view class", VelocityLayoutView.class, view.getClass());
assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
assertEquals("Correct toolbox", toolbox, ((VelocityToolboxView) view).getToolboxConfigLocation());
}
public void testVelocityLayoutViewResolver() throws Exception {
VelocityConfig vc = new VelocityConfig() {
public VelocityEngine getVelocityEngine() {
TestVelocityEngine ve = new TestVelocityEngine();
ve.addTemplate("prefix_test_suffix", new Template());
ve.addTemplate("myLayoutUrl", new Template());
return ve;
}
};
StaticWebApplicationContext wac = new StaticWebApplicationContext();
wac.getBeanFactory().registerSingleton("configurer", vc);
VelocityLayoutViewResolver vr = new VelocityLayoutViewResolver();
vr.setPrefix("prefix_");
vr.setSuffix("_suffix");
vr.setLayoutUrl("myLayoutUrl");
vr.setLayoutKey("myLayoutKey");
vr.setScreenContentKey("myScreenContentKey");
vr.setApplicationContext(wac);
View view = vr.resolveViewName("test", Locale.CANADA);
assertEquals("Correct view class", VelocityLayoutView.class, view.getClass());
assertEquals("Correct URL", "prefix_test_suffix", ((VelocityView) view).getUrl());
// TODO: Need to test actual VelocityLayoutView properties and their functionality!
}
}

View File

@@ -0,0 +1,57 @@
##
## test template for Velocity macro test class
##
NAME
$command.name
AGE
$command.age
MESSAGE
#springMessage("hello") #springMessage("world")
DEFAULTMESSAGE
#springMessageText("no.such.code" "hi") #springMessageText("no.such.code" "planet")
THEME
#springTheme("hello") #springTheme("world")
DEFAULTTHEME
#springThemeText("no.such.code" "hi!") #springThemeText("no.such.code" "planet!")
URL
#springUrl("/aftercontext.html")
FORM1
#springFormInput("command.name" "")
FORM2
#springFormInput("command.name" 'class="myCssClass"')
FORM3
#springFormTextarea("command.name" "")
FORM4
#springFormTextarea("command.name" "rows=10 cols=30")
FORM5
#springFormSingleSelect("command.name" $nameOptionMap "")
FORM6
#springFormMultiSelect("command.spouses" $nameOptionMap "")
FORM7
#springFormRadioButtons("command.name" $nameOptionMap " " "")
FORM8
#springFormCheckboxes("command.spouses" $nameOptionMap " " "")
FORM9
#springFormPasswordInput("command.name" "")
FORM10
#springFormHiddenInput("command.name" "")
ERRORS
#springShowErrors(" " "")

View File

@@ -0,0 +1,23 @@
<?xml version="1.0"?>
<toolbox>
<xhtml>true</xhtml>
<data type="string">
<key>foo</key>
<value>this is foo.</value>
</data>
<tool>
<key>map</key>
<class>java.util.HashMap</class>
</tool>
<tool>
<key>date</key>
<scope>application</scope>
<class>org.apache.velocity.tools.generic.DateTool</class>
</tool>
<tool>
<key>link</key>
<scope>request</scope>
<class>org.apache.velocity.tools.view.tools.LinkTool</class>
</tool>
</toolbox>