Java 5 code style

This commit is contained in:
Juergen Hoeller
2008-11-27 00:27:52 +00:00
parent 6bbc966a21
commit b0790bf5e7
248 changed files with 2374 additions and 3208 deletions

View File

@@ -20,7 +20,6 @@ import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import javax.naming.Binding;
import javax.naming.Context;
import javax.naming.Name;
@@ -57,9 +56,9 @@ public class SimpleNamingContext implements Context {
private final String root;
private final Hashtable boundObjects;
private final Hashtable<String, Object> boundObjects;
private final Hashtable environment = new Hashtable();
private final Hashtable<String, Object> environment = new Hashtable<String, Object>();
/**
@@ -74,32 +73,32 @@ public class SimpleNamingContext implements Context {
*/
public SimpleNamingContext(String root) {
this.root = root;
this.boundObjects = new Hashtable();
this.boundObjects = new Hashtable<String, Object>();
}
/**
* Create a new naming context with the given naming root,
* the given name/object map, and the JNDI environment entries.
*/
public SimpleNamingContext(String root, Hashtable boundObjects, Hashtable environment) {
public SimpleNamingContext(String root, Hashtable<String, Object> boundObjects, Hashtable<String, Object> env) {
this.root = root;
this.boundObjects = boundObjects;
if (environment != null) {
this.environment.putAll(environment);
if (env != null) {
this.environment.putAll(env);
}
}
// Actual implementations of Context methods follow
public NamingEnumeration list(String root) throws NamingException {
public NamingEnumeration<NameClassPair> list(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing name/class pairs under [" + root + "]");
}
return new NameClassPairEnumeration(this, root);
}
public NamingEnumeration listBindings(String root) throws NamingException {
public NamingEnumeration<Binding> listBindings(String root) throws NamingException {
if (logger.isDebugEnabled()) {
logger.debug("Listing bindings under [" + root + "]");
}
@@ -125,8 +124,7 @@ public class SimpleNamingContext implements Context {
if (!name.endsWith("/")) {
name = name + "/";
}
for (Iterator it = this.boundObjects.keySet().iterator(); it.hasNext();) {
String boundName = (String) it.next();
for (String boundName : this.boundObjects.keySet()) {
if (boundName.startsWith(name)) {
return new SimpleNamingContext(name, this.boundObjects, this.environment);
}
@@ -191,7 +189,7 @@ public class SimpleNamingContext implements Context {
return prefix + name;
}
public Hashtable getEnvironment() {
public Hashtable<String, Object> getEnvironment() {
return this.environment;
}
@@ -209,11 +207,11 @@ public class SimpleNamingContext implements Context {
// Unsupported methods follow: no support for javax.naming.Name
public NamingEnumeration list(Name name) throws NamingException {
public NamingEnumeration<NameClassPair> list(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
public NamingEnumeration listBindings(Name name) throws NamingException {
public NamingEnumeration<Binding> listBindings(Name name) throws NamingException {
throw new OperationNotSupportedException("SimpleNamingContext does not support [javax.naming.Name]");
}
@@ -266,19 +264,17 @@ public class SimpleNamingContext implements Context {
}
private static abstract class AbstractNamingEnumeration implements NamingEnumeration {
private static abstract class AbstractNamingEnumeration<T> implements NamingEnumeration<T> {
private Iterator iterator;
private Iterator<T> iterator;
private AbstractNamingEnumeration(SimpleNamingContext context, String proot) throws NamingException {
if (!"".equals(proot) && !proot.endsWith("/")) {
proot = proot + "/";
}
String root = context.root + proot;
Map contents = new HashMap();
Iterator it = context.boundObjects.keySet().iterator();
while (it.hasNext()) {
String boundName = (String) it.next();
Map<String, T> contents = new HashMap<String, T>();
for (String boundName : context.boundObjects.keySet()) {
if (boundName.startsWith(root)) {
int startIndex = root.length();
int endIndex = boundName.indexOf('/', startIndex);
@@ -300,13 +296,13 @@ public class SimpleNamingContext implements Context {
this.iterator = contents.values().iterator();
}
protected abstract Object createObject(String strippedName, Object obj);
protected abstract T createObject(String strippedName, Object obj);
public boolean hasMore() {
return this.iterator.hasNext();
}
public Object next() {
public T next() {
return this.iterator.next();
}
@@ -314,7 +310,7 @@ public class SimpleNamingContext implements Context {
return this.iterator.hasNext();
}
public Object nextElement() {
public T nextElement() {
return this.iterator.next();
}
@@ -323,25 +319,25 @@ public class SimpleNamingContext implements Context {
}
private static class NameClassPairEnumeration extends AbstractNamingEnumeration {
private static class NameClassPairEnumeration extends AbstractNamingEnumeration<NameClassPair> {
private NameClassPairEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
protected Object createObject(String strippedName, Object obj) {
protected NameClassPair createObject(String strippedName, Object obj) {
return new NameClassPair(strippedName, obj.getClass().getName());
}
}
private static class BindingEnumeration extends AbstractNamingEnumeration {
private static class BindingEnumeration extends AbstractNamingEnumeration<Binding> {
private BindingEnumeration(SimpleNamingContext context, String root) throws NamingException {
super(context, root);
}
protected Object createObject(String strippedName, Object obj) {
protected Binding createObject(String strippedName, Object obj) {
return new Binding(strippedName, obj);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -18,7 +18,6 @@ package org.springframework.mock.web;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
@@ -35,7 +34,7 @@ import org.springframework.util.CollectionUtils;
*/
class HeaderValueHolder {
private final List values = new LinkedList();
private final List<Object> values = new LinkedList<Object>();
public void setValue(Object value) {
@@ -47,7 +46,7 @@ class HeaderValueHolder {
this.values.add(value);
}
public void addValues(Collection values) {
public void addValues(Collection<?> values) {
this.values.addAll(values);
}
@@ -55,7 +54,7 @@ class HeaderValueHolder {
CollectionUtils.mergeArrayIntoCollection(values, this.values);
}
public List getValues() {
public List<Object> getValues() {
return Collections.unmodifiableList(this.values);
}
@@ -71,12 +70,11 @@ class HeaderValueHolder {
* @return the corresponding HeaderValueHolder,
* or <code>null</code> if none found
*/
public static HeaderValueHolder getByName(Map headers, String name) {
public static HeaderValueHolder getByName(Map<String, HeaderValueHolder> headers, String name) {
Assert.notNull(name, "Header name must not be null");
for (Iterator it = headers.keySet().iterator(); it.hasNext();) {
String headerName = (String) it.next();
for (String headerName : headers.keySet()) {
if (headerName.equalsIgnoreCase(name)) {
return (HeaderValueHolder) headers.get(headerName);
return headers.get(headerName);
}
}
return null;

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -18,6 +18,9 @@ package org.springframework.mock.web;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Collections;
import java.util.Map;
import java.util.LinkedHashMap;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
@@ -41,7 +44,7 @@ public class MockFilterConfig implements FilterConfig {
private final String filterName;
private final Properties initParameters = new Properties();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
/**
@@ -88,16 +91,16 @@ public class MockFilterConfig implements FilterConfig {
public void addInitParameter(String name, String value) {
Assert.notNull(name, "Parameter name must not be null");
this.initParameters.setProperty(name, value);
this.initParameters.put(name, value);
}
public String getInitParameter(String name) {
Assert.notNull(name, "Parameter name must not be null");
return this.initParameters.getProperty(name);
return this.initParameters.get(name);
}
public Enumeration getInitParameterNames() {
return this.initParameters.keys();
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(this.initParameters.keySet());
}
}

View File

@@ -29,13 +29,12 @@ import java.util.Date;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
@@ -121,7 +120,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
private String remoteHost = DEFAULT_REMOTE_HOST;
/** List of locales in descending order */
private final Vector locales = new Vector();
private final List<Locale> locales = new LinkedList<Locale>();
private boolean secure = false;
@@ -147,7 +146,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
/**
* The key is the lowercase header name; the value is a {@link HeaderValueHolder} object.
*/
private final Hashtable headers = new Hashtable();
private final Map<String, HeaderValueHolder> headers = new Hashtable<String, HeaderValueHolder>();
private String method;
@@ -159,7 +158,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
private String remoteUser;
private final Set userRoles = new HashSet();
private final Set<String> userRoles = new HashSet<String>();
private Principal userPrincipal;
@@ -284,7 +283,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
return this.attributes.get(name);
}
public Enumeration getAttributeNames() {
public Enumeration<String> getAttributeNames() {
checkActive();
return this.attributes.keys();
}
@@ -439,7 +438,7 @@ public class MockHttpServletRequest implements HttpServletRequest {
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public Enumeration getParameterNames() {
public Enumeration<String> getParameterNames() {
return Collections.enumeration(this.parameters.keySet());
}
@@ -545,11 +544,11 @@ public class MockHttpServletRequest implements HttpServletRequest {
}
public Locale getLocale() {
return (Locale) this.locales.get(0);
return this.locales.get(0);
}
public Enumeration getLocales() {
return this.locales.elements();
public Enumeration<Locale> getLocales() {
return Collections.enumeration(this.locales);
}
public void setSecure(boolean secure) {
@@ -679,13 +678,13 @@ public class MockHttpServletRequest implements HttpServletRequest {
return (header != null ? header.getValue().toString() : null);
}
public Enumeration getHeaders(String name) {
public Enumeration<Object> getHeaders(String name) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
return Collections.enumeration(header != null ? header.getValues() : Collections.EMPTY_LIST);
return Collections.enumeration(header != null ? header.getValues() : Collections.emptyList());
}
public Enumeration getHeaderNames() {
return this.headers.keys();
public Enumeration<String> getHeaderNames() {
return Collections.enumeration(this.headers.keySet());
}
public int getIntHeader(String name) {

View File

@@ -88,12 +88,12 @@ public class MockHttpServletResponse implements HttpServletResponse {
// HttpServletResponse properties
//---------------------------------------------------------------------
private final List cookies = new ArrayList();
private final List<Cookie> cookies = new ArrayList<Cookie>();
/**
* The key is the lowercase header name; the value is a {@link HeaderValueHolder} object.
*/
private final Map headers = new HashMap();
private final Map<String, HeaderValueHolder> headers = new HashMap<String, HeaderValueHolder>();
private int status = HttpServletResponse.SC_OK;
@@ -266,13 +266,12 @@ public class MockHttpServletResponse implements HttpServletResponse {
}
public Cookie[] getCookies() {
return (Cookie[]) this.cookies.toArray(new Cookie[this.cookies.size()]);
return this.cookies.toArray(new Cookie[this.cookies.size()]);
}
public Cookie getCookie(String name) {
Assert.notNull(name, "Cookie name must not be null");
for (Iterator it = this.cookies.iterator(); it.hasNext();) {
Cookie cookie = (Cookie) it.next();
for (Cookie cookie : this.cookies) {
if (name.equals(cookie.getName())) {
return cookie;
}
@@ -288,7 +287,7 @@ public class MockHttpServletResponse implements HttpServletResponse {
* Return the names of all specified headers as a Set of Strings.
* @return the <code>Set</code> of header name <code>Strings</code>, or an empty <code>Set</code> if none
*/
public Set getHeaderNames() {
public Set<String> getHeaderNames() {
return this.headers.keySet();
}
@@ -310,7 +309,7 @@ public class MockHttpServletResponse implements HttpServletResponse {
*/
public List getHeaders(String name) {
HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
return (header != null ? header.getValues() : Collections.EMPTY_LIST);
return (header != null ? header.getValues() : Collections.emptyList());
}
/**
@@ -372,11 +371,11 @@ public class MockHttpServletResponse implements HttpServletResponse {
}
public void setDateHeader(String name, long value) {
setHeaderValue(name, new Long(value));
setHeaderValue(name, value);
}
public void addDateHeader(String name, long value) {
addHeaderValue(name, new Long(value));
addHeaderValue(name, value);
}
public void setHeader(String name, String value) {
@@ -388,11 +387,11 @@ public class MockHttpServletResponse implements HttpServletResponse {
}
public void setIntHeader(String name, int value) {
setHeaderValue(name, new Integer(value));
setHeaderValue(name, value);
}
public void addIntHeader(String name, int value) {
addHeaderValue(name, new Integer(value));
addHeaderValue(name, value);
}
private void setHeaderValue(String name, Object value) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -17,12 +17,12 @@
package org.springframework.mock.web;
import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
@@ -60,7 +60,7 @@ public class MockHttpSession implements HttpSession {
private final ServletContext servletContext;
private final Hashtable attributes = new Hashtable();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private boolean invalid = false;
@@ -136,12 +136,12 @@ public class MockHttpSession implements HttpSession {
return getAttribute(name);
}
public Enumeration getAttributeNames() {
return this.attributes.keys();
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public String[] getValueNames() {
return (String[]) this.attributes.keySet().toArray(new String[this.attributes.size()]);
return this.attributes.keySet().toArray(new String[this.attributes.size()]);
}
public void setAttribute(String name, Object value) {
@@ -177,9 +177,9 @@ public class MockHttpSession implements HttpSession {
* Clear all of this session's attributes.
*/
public void clearAttributes() {
for (Iterator it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
String name = entry.getKey();
Object value = entry.getValue();
it.remove();
if (value instanceof HttpSessionBindingListener) {
@@ -212,14 +212,14 @@ public class MockHttpSession implements HttpSession {
* @return a representation of this session's serialized state
*/
public Serializable serializeState() {
HashMap state = new HashMap();
for (Iterator it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
HashMap<String, Serializable> state = new HashMap<String, Serializable>();
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
String name = entry.getKey();
Object value = entry.getValue();
it.remove();
if (value instanceof Serializable) {
state.put(name, value);
state.put(name, (Serializable) value);
}
else {
// Not serializable... Servlet containers usually automatically
@@ -237,9 +237,10 @@ public class MockHttpSession implements HttpSession {
* created by {@link #serializeState()}.
* @param state a representation of this session's serialized state
*/
@SuppressWarnings("unchecked")
public void deserializeState(Serializable state) {
Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");
this.attributes.putAll((Map) state);
this.attributes.putAll((Map<String, Object>) state);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -40,7 +40,7 @@ import org.springframework.web.multipart.MultipartHttpServletRequest;
*/
public class MockMultipartHttpServletRequest extends MockHttpServletRequest implements MultipartHttpServletRequest {
private final Map multipartFiles = new LinkedHashMap(4);
private final Map<String, MultipartFile> multipartFiles = new LinkedHashMap<String, MultipartFile>();
/**
@@ -53,15 +53,15 @@ public class MockMultipartHttpServletRequest extends MockHttpServletRequest impl
this.multipartFiles.put(file.getName(), file);
}
public Iterator getFileNames() {
public Iterator<String> getFileNames() {
return getFileMap().keySet().iterator();
}
public MultipartFile getFile(String name) {
return (MultipartFile) this.multipartFiles.get(name);
return this.multipartFiles.get(name);
}
public Map getFileMap() {
public Map<String, MultipartFile> getFileMap() {
return Collections.unmodifiableMap(this.multipartFiles);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -17,9 +17,10 @@
package org.springframework.mock.web;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@@ -59,7 +60,7 @@ public class MockPageContext extends PageContext {
private final ServletConfig servletConfig;
private final Hashtable attributes = new Hashtable();
private final Map<String, Object> attributes = new HashMap<String, Object>();
private JspWriter out;
@@ -244,11 +245,12 @@ public class MockPageContext extends PageContext {
}
}
public Enumeration getAttributeNames() {
return this.attributes.keys();
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public Enumeration getAttributeNamesInScope(int scope) {
@SuppressWarnings("unchecked")
public Enumeration<String> getAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return getAttributeNames();

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* 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.
@@ -16,9 +16,10 @@
package org.springframework.mock.web;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Properties;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@@ -40,7 +41,7 @@ public class MockServletConfig implements ServletConfig {
private final String servletName;
private final Properties initParameters = new Properties();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
/**
@@ -78,25 +79,25 @@ public class MockServletConfig implements ServletConfig {
public String getServletName() {
return servletName;
return this.servletName;
}
public ServletContext getServletContext() {
return servletContext;
return this.servletContext;
}
public void addInitParameter(String name, String value) {
Assert.notNull(name, "Parameter name must not be null");
this.initParameters.setProperty(name, value);
this.initParameters.put(name, value);
}
public String getInitParameter(String name) {
Assert.notNull(name, "Parameter name must not be null");
return this.initParameters.getProperty(name);
return this.initParameters.get(name);
}
public Enumeration getInitParameterNames() {
return this.initParameters.keys();
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(this.initParameters.keySet());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -24,12 +24,11 @@ import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javax.activation.FileTypeMap;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
@@ -90,11 +89,11 @@ public class MockServletContext implements ServletContext {
private String contextPath = "";
private final Map contexts = new HashMap();
private final Map<String, ServletContext> contexts = new HashMap<String, ServletContext>();
private final Properties initParameters = new Properties();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
private final Hashtable attributes = new Hashtable();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private String servletContextName = "MockServletContext";
@@ -174,7 +173,7 @@ public class MockServletContext implements ServletContext {
if (this.contextPath.equals(contextPath)) {
return this;
}
return (ServletContext) this.contexts.get(contextPath);
return this.contexts.get(contextPath);
}
public int getMajorVersion() {
@@ -198,10 +197,10 @@ public class MockServletContext implements ServletContext {
if (ObjectUtils.isEmpty(fileList)) {
return null;
}
Set resourcePaths = new LinkedHashSet(fileList.length);
for (int i = 0; i < fileList.length; i++) {
String resultPath = actualPath + fileList[i];
if (resource.createRelative(fileList[i]).getFile().isDirectory()) {
Set<String> resourcePaths = new LinkedHashSet<String>(fileList.length);
for (String fileEntry : fileList) {
String resultPath = actualPath + fileEntry;
if (resource.createRelative(fileEntry).getFile().isDirectory()) {
resultPath += "/";
}
resourcePaths.add(resultPath);
@@ -260,12 +259,12 @@ public class MockServletContext implements ServletContext {
return null;
}
public Enumeration getServlets() {
return Collections.enumeration(Collections.EMPTY_SET);
public Enumeration<Servlet> getServlets() {
return Collections.enumeration(new HashSet<Servlet>());
}
public Enumeration getServletNames() {
return Collections.enumeration(Collections.EMPTY_SET);
public Enumeration<String> getServletNames() {
return Collections.enumeration(new HashSet<String>());
}
public void log(String message) {
@@ -297,16 +296,16 @@ public class MockServletContext implements ServletContext {
public String getInitParameter(String name) {
Assert.notNull(name, "Parameter name must not be null");
return this.initParameters.getProperty(name);
return this.initParameters.get(name);
}
public void addInitParameter(String name, String value) {
Assert.notNull(name, "Parameter name must not be null");
this.initParameters.setProperty(name, value);
this.initParameters.put(name, value);
}
public Enumeration getInitParameterNames() {
return this.initParameters.keys();
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(this.initParameters.keySet());
}
public Object getAttribute(String name) {
@@ -314,8 +313,8 @@ public class MockServletContext implements ServletContext {
return this.attributes.get(name);
}
public Enumeration getAttributeNames() {
return this.attributes.keys();
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public void setAttribute(String name, Object value) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -19,9 +19,8 @@ package org.springframework.mock.web.portlet;
import java.io.IOException;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.portlet.ActionResponse;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
@@ -29,7 +28,6 @@ import javax.portlet.PortletModeException;
import javax.portlet.WindowState;
import javax.portlet.WindowStateException;
import org.springframework.core.CollectionFactory;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
@@ -48,7 +46,7 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes
private String redirectedUrl;
private final Map renderParameters = new LinkedHashMap(16);
private final Map<String, String[]> renderParameters = new LinkedHashMap<String, String[]>();
/**
@@ -120,7 +118,7 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String");
Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]");
this.renderParameters.put(entry.getKey(), entry.getValue());
this.renderParameters.put((String) entry.getKey(), (String[]) entry.getValue());
}
}
@@ -133,8 +131,9 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes
this.renderParameters.put(key, new String[] {value});
}
public String getRenderParameter(String name) {
String[] arr = (String[]) this.renderParameters.get(name);
public String getRenderParameter(String key) {
Assert.notNull(key, "Parameter key must not be null");
String[] arr = this.renderParameters.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
@@ -149,7 +148,7 @@ public class MockActionResponse extends MockPortletResponse implements ActionRes
public String[] getRenderParameterValues(String key) {
Assert.notNull(key, "Parameter key must not be null");
return (String[]) this.renderParameters.get(key);
return this.renderParameters.get(key);
}
public Iterator getRenderParameterNames() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -39,7 +39,7 @@ import org.springframework.web.portlet.multipart.MultipartActionRequest;
*/
public class MockMultipartActionRequest extends MockActionRequest implements MultipartActionRequest {
private final Map multipartFiles = new LinkedHashMap(4);
private final Map<String, MultipartFile> multipartFiles = new LinkedHashMap<String, MultipartFile>();
/**
@@ -52,15 +52,15 @@ public class MockMultipartActionRequest extends MockActionRequest implements Mul
this.multipartFiles.put(file.getName(), file);
}
public Iterator getFileNames() {
public Iterator<String> getFileNames() {
return getFileMap().keySet().iterator();
}
public MultipartFile getFile(String name) {
return (MultipartFile) this.multipartFiles.get(name);
return this.multipartFiles.get(name);
}
public Map getFileMap() {
public Map<String, MultipartFile> getFileMap() {
return Collections.unmodifiableMap(this.multipartFiles);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* 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.
@@ -16,11 +16,12 @@
package org.springframework.mock.web.portlet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import java.util.Map;
import javax.portlet.PortalContext;
import javax.portlet.PortletMode;
import javax.portlet.WindowState;
@@ -34,11 +35,11 @@ import javax.portlet.WindowState;
*/
public class MockPortalContext implements PortalContext {
private final Properties properties = new Properties();
private final Map<String, String> properties = new HashMap<String, String>();
private final Vector portletModes;
private final List<PortletMode> portletModes;
private final Vector windowStates;
private final List<WindowState> windowStates;
/**
@@ -49,12 +50,12 @@ public class MockPortalContext implements PortalContext {
* @see javax.portlet.WindowState
*/
public MockPortalContext() {
this.portletModes = new Vector(3);
this.portletModes = new ArrayList<PortletMode>(3);
this.portletModes.add(PortletMode.VIEW);
this.portletModes.add(PortletMode.EDIT);
this.portletModes.add(PortletMode.HELP);
this.windowStates = new Vector(3);
this.windowStates = new ArrayList<WindowState>(3);
this.windowStates.add(WindowState.NORMAL);
this.windowStates.add(WindowState.MAXIMIZED);
this.windowStates.add(WindowState.MINIMIZED);
@@ -67,9 +68,9 @@ public class MockPortalContext implements PortalContext {
* @see javax.portlet.PortletMode
* @see javax.portlet.WindowState
*/
public MockPortalContext(List supportedPortletModes, List supportedWindowStates) {
this.portletModes = new Vector(supportedPortletModes);
this.windowStates = new Vector(supportedWindowStates);
public MockPortalContext(List<PortletMode> supportedPortletModes, List<WindowState> supportedWindowStates) {
this.portletModes = new ArrayList<PortletMode>(supportedPortletModes);
this.windowStates = new ArrayList<WindowState>(supportedWindowStates);
}
@@ -77,20 +78,24 @@ public class MockPortalContext implements PortalContext {
return "MockPortal/1.0";
}
public void setProperty(String name, String value) {
this.properties.put(name, value);
}
public String getProperty(String name) {
return this.properties.getProperty(name);
return this.properties.get(name);
}
public Enumeration getPropertyNames() {
return this.properties.propertyNames();
public Enumeration<String> getPropertyNames() {
return Collections.enumeration(this.properties.keySet());
}
public Enumeration getSupportedPortletModes() {
return this.portletModes.elements();
public Enumeration<PortletMode> getSupportedPortletModes() {
return Collections.enumeration(this.portletModes);
}
public Enumeration getSupportedWindowStates() {
return this.windowStates.elements();
public Enumeration<WindowState> getSupportedWindowStates() {
return Collections.enumeration(this.windowStates);
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -19,9 +19,11 @@ package org.springframework.mock.web.portlet;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.LinkedHashMap;
import java.util.Collections;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
@@ -40,9 +42,9 @@ public class MockPortletConfig implements PortletConfig {
private final String portletName;
private final HashMap resourceBundles = new HashMap();
private final Map<Locale, ResourceBundle> resourceBundles = new HashMap<Locale, ResourceBundle>();
private final Properties initParameters = new Properties();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
/**
@@ -94,21 +96,21 @@ public class MockPortletConfig implements PortletConfig {
public ResourceBundle getResourceBundle(Locale locale) {
Assert.notNull(locale, "Locale must not be null");
return (ResourceBundle) this.resourceBundles.get(locale);
return this.resourceBundles.get(locale);
}
public void addInitParameter(String name, String value) {
Assert.notNull(name, "Parameter name must not be null");
this.initParameters.setProperty(name, value);
this.initParameters.put(name, value);
}
public String getInitParameter(String name) {
Assert.notNull(name, "Parameter name must not be null");
return this.initParameters.getProperty(name);
return this.initParameters.get(name);
}
public Enumeration getInitParameterNames() {
return this.initParameters.keys();
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(this.initParameters.keySet());
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* 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.
@@ -21,12 +21,12 @@ import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Properties;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequestDispatcher;
@@ -57,9 +57,9 @@ public class MockPortletContext implements PortletContext {
private final ResourceLoader resourceLoader;
private final Hashtable attributes = new Hashtable();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private final Properties initParameters = new Properties();
private final Map<String, String> initParameters = new LinkedHashMap<String, String>();
private String portletContextName = "MockPortletContext";
@@ -171,15 +171,15 @@ public class MockPortletContext implements PortletContext {
}
}
public Set getResourcePaths(String path) {
public Set<String> getResourcePaths(String path) {
Resource resource = this.resourceLoader.getResource(getResourceLocation(path));
try {
File file = resource.getFile();
String[] fileList = file.list();
String prefix = (path.endsWith("/") ? path : path + "/");
Set resourcePaths = new HashSet(fileList.length);
for (int i = 0; i < fileList.length; i++) {
resourcePaths.add(prefix + fileList[i]);
Set<String> resourcePaths = new HashSet<String>(fileList.length);
for (String fileEntry : fileList) {
resourcePaths.add(prefix + fileEntry);
}
return resourcePaths;
}
@@ -204,8 +204,8 @@ public class MockPortletContext implements PortletContext {
return this.attributes.get(name);
}
public Enumeration getAttributeNames() {
return this.attributes.keys();
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public void setAttribute(String name, Object value) {
@@ -223,16 +223,16 @@ public class MockPortletContext implements PortletContext {
public void addInitParameter(String name, String value) {
Assert.notNull(name, "Parameter name must not be null");
this.initParameters.setProperty(name, value);
this.initParameters.put(name, value);
}
public String getInitParameter(String name) {
Assert.notNull(name, "Parameter name must not be null");
return this.initParameters.getProperty(name);
return this.initParameters.get(name);
}
public Enumeration getInitParameterNames() {
return this.initParameters.keys();
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(this.initParameters.keySet());
}
public void log(String message) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -42,9 +42,9 @@ public class MockPortletPreferences implements PortletPreferences {
private PreferencesValidator preferencesValidator;
private final Map preferences = new LinkedHashMap(16);
private final Map<String, String[]> preferences = new LinkedHashMap<String, String[]>();
private final Set readOnly = new HashSet();
private final Set<String> readOnly = new HashSet<String>();
public void setReadOnly(String key, boolean readOnly) {
@@ -64,13 +64,13 @@ public class MockPortletPreferences implements PortletPreferences {
public String getValue(String key, String def) {
Assert.notNull(key, "Key must not be null");
String[] values = (String[]) this.preferences.get(key);
String[] values = this.preferences.get(key);
return (values != null && values.length > 0 ? values[0] : def);
}
public String[] getValues(String key, String[] def) {
Assert.notNull(key, "Key must not be null");
String[] values = (String[]) this.preferences.get(key);
String[] values = this.preferences.get(key);
return (values != null && values.length > 0 ? values : def);
}
@@ -86,11 +86,11 @@ public class MockPortletPreferences implements PortletPreferences {
this.preferences.put(key, values);
}
public Enumeration getNames() {
public Enumeration<String> getNames() {
return Collections.enumeration(this.preferences.keySet());
}
public Map getMap() {
public Map<String, String[]> getMap() {
return Collections.unmodifiableMap(this.preferences);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -20,16 +20,12 @@ import java.security.Principal;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.Vector;
import javax.portlet.PortalContext;
import javax.portlet.PortletContext;
import javax.portlet.PortletMode;
@@ -64,11 +60,11 @@ public class MockPortletRequest implements PortletRequest {
private PortletPreferences portletPreferences = new MockPortletPreferences();
private final Map properties = new LinkedHashMap(16);
private final Map<String, List<String>> properties = new LinkedHashMap<String, List<String>>();
private final Hashtable attributes = new Hashtable();
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private final Map parameters = new LinkedHashMap(16);
private final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
private String authType = null;
@@ -78,15 +74,15 @@ public class MockPortletRequest implements PortletRequest {
private Principal userPrincipal = null;
private final Set userRoles = new HashSet();
private final Set<String> userRoles = new HashSet<String>();
private boolean secure = false;
private boolean requestedSessionIdValid = true;
private final Vector responseContentTypes = new Vector();
private final List<String> responseContentTypes = new LinkedList<String>();
private final Vector locales = new Vector();
private final List<Locale> locales = new LinkedList<Locale>();
private String scheme = "http";
@@ -227,7 +223,7 @@ public class MockPortletRequest implements PortletRequest {
*/
public void setProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
List list = new LinkedList();
List<String> list = new LinkedList<String>();
list.add(value);
this.properties.put(key, list);
}
@@ -239,12 +235,12 @@ public class MockPortletRequest implements PortletRequest {
*/
public void addProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
List oldList = (List) this.properties.get(key);
List<String> oldList = this.properties.get(key);
if (oldList != null) {
oldList.add(value);
}
else {
List list = new LinkedList();
List<String> list = new LinkedList<String>();
list.add(value);
this.properties.put(key, list);
}
@@ -252,16 +248,16 @@ public class MockPortletRequest implements PortletRequest {
public String getProperty(String key) {
Assert.notNull(key, "Property key must not be null");
List list = (List) this.properties.get(key);
List list = this.properties.get(key);
return (list != null && list.size() > 0 ? (String) list.get(0) : null);
}
public Enumeration getProperties(String key) {
public Enumeration<String> getProperties(String key) {
Assert.notNull(key, "property key must not be null");
return Collections.enumeration((List) this.properties.get(key));
return Collections.enumeration(this.properties.get(key));
}
public Enumeration getPropertyNames() {
public Enumeration<String> getPropertyNames() {
return Collections.enumeration(this.properties.keySet());
}
@@ -314,20 +310,15 @@ public class MockPortletRequest implements PortletRequest {
return this.attributes.get(name);
}
public Enumeration getAttributeNames() {
public Enumeration<String> getAttributeNames() {
checkActive();
return this.attributes.keys();
return Collections.enumeration(this.attributes.keySet());
}
public void setParameters(Map parameters) {
public void setParameters(Map<String, String[]> parameters) {
Assert.notNull(parameters, "Parameters Map must not be null");
this.parameters.clear();
for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String");
Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]");
this.parameters.put(entry.getKey(), entry.getValue());
}
this.parameters.putAll(parameters);
}
public void setParameter(String key, String value) {
@@ -347,7 +338,7 @@ public class MockPortletRequest implements PortletRequest {
}
public void addParameter(String name, String[] values) {
String[] oldArr = (String[]) this.parameters.get(name);
String[] oldArr = this.parameters.get(name);
if (oldArr != null) {
String[] newArr = new String[oldArr.length + values.length];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
@@ -360,16 +351,16 @@ public class MockPortletRequest implements PortletRequest {
}
public String getParameter(String name) {
String[] arr = (String[]) this.parameters.get(name);
String[] arr = this.parameters.get(name);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public Enumeration getParameterNames() {
public Enumeration<String> getParameterNames() {
return Collections.enumeration(this.parameters.keySet());
}
public String[] getParameterValues(String name) {
return (String[]) this.parameters.get(name);
return this.parameters.get(name);
}
public Map getParameterMap() {
@@ -421,11 +412,11 @@ public class MockPortletRequest implements PortletRequest {
}
public String getResponseContentType() {
return (String) this.responseContentTypes.get(0);
return this.responseContentTypes.get(0);
}
public Enumeration getResponseContentTypes() {
return this.responseContentTypes.elements();
public Enumeration<String> getResponseContentTypes() {
return Collections.enumeration(this.responseContentTypes);
}
public void addLocale(Locale locale) {
@@ -437,11 +428,11 @@ public class MockPortletRequest implements PortletRequest {
}
public Locale getLocale() {
return (Locale) this.locales.get(0);
return this.locales.get(0);
}
public Enumeration getLocales() {
return this.locales.elements();
public Enumeration<Locale> getLocales() {
return Collections.enumeration(this.locales);
}
public void setScheme(String scheme) {
@@ -449,7 +440,7 @@ public class MockPortletRequest implements PortletRequest {
}
public String getScheme() {
return scheme;
return this.scheme;
}
public void setServerName(String serverName) {
@@ -457,7 +448,7 @@ public class MockPortletRequest implements PortletRequest {
}
public String getServerName() {
return serverName;
return this.serverName;
}
public void setServerPort(int serverPort) {
@@ -465,7 +456,7 @@ public class MockPortletRequest implements PortletRequest {
}
public int getServerPort() {
return serverPort;
return this.serverPort;
}
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -36,7 +36,7 @@ public class MockPortletResponse implements PortletResponse {
private final PortalContext portalContext;
private final Map properties = new LinkedHashMap(16);
private final Map<String, String[]> properties = new LinkedHashMap<String, String[]>();
/**
@@ -61,7 +61,7 @@ public class MockPortletResponse implements PortletResponse {
* defining the supported PortletModes and WindowStates.
*/
public PortalContext getPortalContext() {
return portalContext;
return this.portalContext;
}
@@ -71,7 +71,7 @@ public class MockPortletResponse implements PortletResponse {
public void addProperty(String key, String value) {
Assert.notNull(key, "Property key must not be null");
String[] oldArr = (String[]) this.properties.get(key);
String[] oldArr = this.properties.get(key);
if (oldArr != null) {
String[] newArr = new String[oldArr.length + 1];
System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
@@ -94,13 +94,13 @@ public class MockPortletResponse implements PortletResponse {
public String getProperty(String key) {
Assert.notNull(key, "Property key must not be null");
String[] arr = (String[]) this.properties.get(key);
String[] arr = this.properties.get(key);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getProperties(String key) {
Assert.notNull(key, "Property key must not be null");
return (String[]) this.properties.get(key);
return this.properties.get(key);
}
public String encodeURL(String path) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2006 the original author or authors.
* 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.
@@ -16,9 +16,10 @@
package org.springframework.mock.web.portlet;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.HashMap;
import java.util.Map;
import javax.portlet.PortletContext;
import javax.portlet.PortletSession;
@@ -44,9 +45,9 @@ public class MockPortletSession implements PortletSession {
private final PortletContext portletContext;
private final Hashtable portletAttributes = new Hashtable();
private final Map<String, Object> portletAttributes = new HashMap<String, Object>();
private final Hashtable applicationAttributes = new Hashtable();
private final Map<String, Object> applicationAttributes = new HashMap<String, Object>();
private boolean invalid = false;
@@ -84,16 +85,16 @@ public class MockPortletSession implements PortletSession {
return null;
}
public Enumeration getAttributeNames() {
return this.portletAttributes.keys();
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.portletAttributes.keySet());
}
public Enumeration getAttributeNames(int scope) {
public Enumeration<String> getAttributeNames(int scope) {
if (scope == PortletSession.PORTLET_SCOPE) {
return this.portletAttributes.keys();
return Collections.enumeration(this.portletAttributes.keySet());
}
else if (scope == PortletSession.APPLICATION_SCOPE) {
return this.applicationAttributes.keys();
return Collections.enumeration(this.applicationAttributes.keySet());
}
return null;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -59,7 +59,7 @@ public class MockPortletURL implements PortletURL {
private PortletMode portletMode;
private final Map parameters = new LinkedHashMap(16);
private final Map<String, String[]> parameters = new LinkedHashMap<String, String[]>();
private boolean secure = false;
@@ -116,24 +116,24 @@ public class MockPortletURL implements PortletURL {
Map.Entry entry = (Map.Entry) it.next();
Assert.isTrue(entry.getKey() instanceof String, "Key must be of type String");
Assert.isTrue(entry.getValue() instanceof String[], "Value must be of type String[]");
this.parameters.put(entry.getKey(), entry.getValue());
this.parameters.put((String) entry.getKey(), (String[]) entry.getValue());
}
}
public Set getParameterNames() {
public Set<String> getParameterNames() {
return this.parameters.keySet();
}
public String getParameter(String name) {
String[] arr = (String[]) this.parameters.get(name);
String[] arr = this.parameters.get(name);
return (arr != null && arr.length > 0 ? arr[0] : null);
}
public String[] getParameterValues(String name) {
return (String[]) this.parameters.get(name);
return this.parameters.get(name);
}
public Map getParameterMap() {
public Map<String, String[]> getParameterMap() {
return Collections.unmodifiableMap(this.parameters);
}
@@ -142,33 +142,13 @@ public class MockPortletURL implements PortletURL {
}
public boolean isSecure() {
return secure;
}
public String toString() {
StringBuffer query = new StringBuffer();
query.append(encodeParameter("urlType", this.urlType));
if (this.windowState != null) {
query.append(";" + encodeParameter("windowState", this.windowState.toString()));
}
if (this.portletMode != null) {
query.append(";" + encodeParameter("portletMode", this.portletMode.toString()));
}
for (Iterator it = this.parameters.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
String[] values = (String[]) entry.getValue();
query.append(";" + encodeParameter("param_" + name, values));
}
return (this.secure ? "https:" : "http:") +
"//localhost/mockportlet?" + query.toString();
return this.secure;
}
private String encodeParameter(String name, String value) {
try {
return URLEncoder.encode(name, ENCODING) + "=" +
URLEncoder.encode(value, ENCODING);
return URLEncoder.encode(name, ENCODING) + "=" + URLEncoder.encode(value, ENCODING);
}
catch (UnsupportedEncodingException ex) {
return null;
@@ -177,17 +157,34 @@ public class MockPortletURL implements PortletURL {
private String encodeParameter(String name, String[] values) {
try {
StringBuffer buf = new StringBuffer();
StringBuilder sb = new StringBuilder();
for (int i = 0, n = values.length; i < n; i++) {
buf.append((i > 0 ? ";" : "") +
sb.append((i > 0 ? ";" : "") +
URLEncoder.encode(name, ENCODING) + "=" +
URLEncoder.encode(values[i], ENCODING));
}
return buf.toString();
return sb.toString();
}
catch (UnsupportedEncodingException ex) {
return null;
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(encodeParameter("urlType", this.urlType));
if (this.windowState != null) {
sb.append(";").append(encodeParameter("windowState", this.windowState.toString()));
}
if (this.portletMode != null) {
sb.append(";").append(encodeParameter("portletMode", this.portletMode.toString()));
}
for (Map.Entry<String, String[]> entry : this.parameters.entrySet()) {
sb.append(";").append(encodeParameter("param_" + entry.getKey(), entry.getValue()));
}
return (this.secure ? "https:" : "http:") +
"//localhost/mockportlet?" + sb.toString();
}
}

View File

@@ -59,7 +59,10 @@ import org.springframework.util.Assert;
* @see #contextKey
* @see #getContext
* @see #getConfigLocations
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class AbstractDependencyInjectionSpringContextTests extends AbstractSingleSpringContextTests {
/**

View File

@@ -65,7 +65,10 @@ import org.springframework.util.StringUtils;
* @see #contextKey()
* @see #loadContext(Object)
* @see #getApplicationContext()
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class AbstractSingleSpringContextTests extends AbstractSpringContextTests {
/** Application context this test will run against */

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -56,7 +56,10 @@ import org.springframework.util.StringUtils;
* @see AbstractDependencyInjectionSpringContextTests
* @see AbstractTransactionalSpringContextTests
* @see AbstractTransactionalDataSourceSpringContextTests
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class AbstractSpringContextTests extends ConditionalTestCase {
/**
@@ -64,7 +67,8 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
* contexts. This needs to be static, as JUnit tests are destroyed and
* recreated between running individual test methods.
*/
private static Map contextKeyToContextMap = new HashMap();
private static Map<String, ConfigurableApplicationContext> contextKeyToContextMap =
new HashMap<String, ConfigurableApplicationContext>();
/**
@@ -80,12 +84,11 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
super(name);
}
/**
* Explicitly add an ApplicationContext instance under a given key.
* <p>
* This is not meant to be used by subclasses. It is rather exposed for
* <p>This is not meant to be used by subclasses. It is rather exposed for
* special test suite environments.
*
* @param key the context key
* @param context the ApplicationContext instance
*/
@@ -96,7 +99,6 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
/**
* Return whether there is a cached context for the given key.
*
* @param key the context key
*/
protected final boolean hasCachedContext(Object key) {
@@ -104,38 +106,29 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
}
/**
* <p>
* Determines if the supplied context <code>key</code> is <em>empty</em>.
* </p>
* <p>
* By default, <code>null</code> values, empty strings, and zero-length
* Determine if the supplied context <code>key</code> is <em>empty</em>.
* <p>By default, <code>null</code> values, empty strings, and zero-length
* arrays are considered <em>empty</em>.
* </p>
*
* @param key the context key to check
* @return <code>true</code> if the supplied context key is empty.
* @return <code>true</code> if the supplied context key is empty
*/
protected boolean isContextKeyEmpty(Object key) {
return (key == null) || ((key instanceof String) && !StringUtils.hasText((String) key))
|| ((key instanceof Object[]) && ObjectUtils.isEmpty((Object[]) key));
return (key == null) || ((key instanceof String) && !StringUtils.hasText((String) key)) ||
((key instanceof Object[]) && ObjectUtils.isEmpty((Object[]) key));
}
/**
* Obtain an ApplicationContext for the given key, potentially cached.
*
* @param key the context key; may be <code>null</code>.
* @return the corresponding ApplicationContext instance (potentially
* cached), or <code>null</code> if the provided <code>key</code>
* is <em>empty</em>.
* @return the corresponding ApplicationContext instance (potentially cached),
* or <code>null</code> if the provided <code>key</code> is <em>empty</em>
*/
protected final ConfigurableApplicationContext getContext(Object key) throws Exception {
if (isContextKeyEmpty(key)) {
return null;
}
String keyString = contextKeyString(key);
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) contextKeyToContextMap.get(keyString);
ConfigurableApplicationContext ctx = contextKeyToContextMap.get(keyString);
if (ctx == null) {
ctx = loadContext(key);
ctx.registerShutdownHook();
@@ -147,13 +140,12 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
/**
* Mark the context with the given key as dirty. This will cause the cached
* context to be reloaded before the next test case is executed.
* <p>
* Call this method only if you change the state of a singleton bean,
* <p>Call this method only if you change the state of a singleton bean,
* potentially affecting future tests.
*/
protected final void setDirty(Object contextKey) {
String keyString = contextKeyString(contextKey);
ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) contextKeyToContextMap.remove(keyString);
ConfigurableApplicationContext ctx = contextKeyToContextMap.remove(keyString);
if (ctx != null) {
ctx.close();
}
@@ -162,7 +154,6 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
/**
* Subclasses can override this to return a String representation of their
* context key for use in caching and logging.
*
* @param contextKey the context key
*/
protected String contextKeyString(Object contextKey) {
@@ -171,9 +162,7 @@ public abstract class AbstractSpringContextTests extends ConditionalTestCase {
/**
* Load a new ApplicationContext for the given key.
* <p>
* To be implemented by subclasses.
*
* <p>To be implemented by subclasses.
* @param key the context key
* @return the corresponding ApplicationContext instance (new)
*/

View File

@@ -45,7 +45,10 @@ import org.springframework.util.StringUtils;
* @since 1.1.1
* @see #setDataSource(javax.sql.DataSource)
* @see #getJdbcTemplate()
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class AbstractTransactionalDataSourceSpringContextTests
extends AbstractTransactionalSpringContextTests {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -26,46 +26,46 @@ import org.springframework.transaction.support.DefaultTransactionDefinition;
* Convenient base class for JUnit 3.8 based tests that should occur in a
* transaction, but normally will roll the transaction back on the completion of
* each test.
* <p>
* This is useful in a range of circumstances, allowing the following benefits:
*
* <p>This is useful in a range of circumstances, allowing the following benefits:
* <ul>
* <li>Ability to delete or insert any data in the database, without affecting
* other tests
* <li>Providing a transactional context for any code requiring a transaction
* <li>Ability to write anything to the database without any need to clean up.
* </ul>
* <p>
* This class is typically very fast, compared to traditional setup/teardown
*
* <p>This class is typically very fast, compared to traditional setup/teardown
* scripts.
* <p>
* If data should be left in the database, call the {@link #setComplete()}
*
* <p>If data should be left in the database, call the {@link #setComplete()}
* method in each test. The {@link #setDefaultRollback "defaultRollback"}
* property, which defaults to "true", determines whether transactions will
* complete by default.
* <p>
* It is even possible to end the transaction early; for example, to verify lazy
*
* <p>It is even possible to end the transaction early; for example, to verify lazy
* loading behavior of an O/R mapping tool. (This is a valuable away to avoid
* unexpected errors when testing a web UI, for example.) Simply call the
* {@link #endTransaction()} method. Execution will then occur without a
* transactional context.
* <p>
* The {@link #startNewTransaction()} method may be called after a call to
*
* <p>The {@link #startNewTransaction()} method may be called after a call to
* {@link #endTransaction()} if you wish to create a new transaction, quite
* independent of the old transaction. The new transaction's default fate will
* be to roll back, unless {@link #setComplete()} is called again during the
* scope of the new transaction. Any number of transactions may be created and
* ended in this way. The final transaction will automatically be rolled back
* when the test case is torn down.
* <p>
* Transactional behavior requires a single bean in the context implementing the
*
* <p>Transactional behavior requires a single bean in the context implementing the
* {@link PlatformTransactionManager} interface. This will be set by the
* superclass's Dependency Injection mechanism. If using the superclass's Field
* Injection mechanism, the implementation should be named "transactionManager".
* This mechanism allows the use of the
* {@link AbstractDependencyInjectionSpringContextTests} superclass even when
* there is more than one transaction manager in the context.
* <p>
* <b>This base class can also be used without transaction management, if no
*
* <p><b>This base class can also be used without transaction management, if no
* PlatformTransactionManager bean is found in the context provided.</b> Be
* careful about using this mode, as it allows the potential to permanently
* modify data. This mode is available only if dependency checking is turned off
@@ -77,49 +77,51 @@ import org.springframework.transaction.support.DefaultTransactionDefinition;
* @author Juergen Hoeller
* @author Sam Brannen
* @since 1.1.1
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class AbstractTransactionalSpringContextTests extends AbstractDependencyInjectionSpringContextTests {
/** The transaction manager to use */
protected PlatformTransactionManager transactionManager;
protected PlatformTransactionManager transactionManager;
/** Should we roll back by default? */
private boolean defaultRollback = true;
private boolean defaultRollback = true;
/** Should we commit the current transaction? */
private boolean complete = false;
private boolean complete = false;
/** Number of transactions started */
private int transactionsStarted = 0;
private int transactionsStarted = 0;
/**
* Transaction definition used by this test class: by default, a plain
* DefaultTransactionDefinition. Subclasses can change this to cause
* different behavior.
*/
protected TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();
protected TransactionDefinition transactionDefinition= new DefaultTransactionDefinition();
/**
* TransactionStatus for this test. Typical subclasses won't need to use it.
*/
protected TransactionStatus transactionStatus;
protected TransactionStatus transactionStatus;
/**
* Default constructor for AbstractTransactionalSpringContextTests.
*/
public AbstractTransactionalSpringContextTests() {
}
/**
* Constructor for AbstractTransactionalSpringContextTests with a JUnit
* name.
* Constructor for AbstractTransactionalSpringContextTests with a JUnit name.
*/
public AbstractTransactionalSpringContextTests(final String name) {
public AbstractTransactionalSpringContextTests(String name) {
super(name);
}
/**
* Specify the transaction manager to use. No transaction management will be
* available if this is not set. Populated through dependency injection by
@@ -128,44 +130,32 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
* This mode works only if dependency checking is turned off in the
* {@link AbstractDependencyInjectionSpringContextTests} superclass.
*/
public void setTransactionManager(final PlatformTransactionManager transactionManager) {
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
/**
* Get the <em>default rollback</em> flag for this test.
*
* @see #setDefaultRollback(boolean)
* @return The <em>default rollback</em> flag.
*/
protected boolean isDefaultRollback() {
return this.defaultRollback;
}
/**
* Subclasses can set this value in their constructor to change the default,
* which is always to roll the transaction back.
*/
public void setDefaultRollback(final boolean defaultRollback) {
this.defaultRollback = defaultRollback;
}
/**
* Get the <em>default rollback</em> flag for this test.
* @see #setDefaultRollback(boolean)
* @return The <em>default rollback</em> flag.
*/
protected boolean isDefaultRollback() {
return this.defaultRollback;
}
/**
* <p>
* Determines whether or not to rollback transactions for the current test.
* </p>
* <p>
* The default implementation delegates to {@link #isDefaultRollback()}.
* <p>The default implementation delegates to {@link #isDefaultRollback()}.
* Subclasses can override as necessary.
* </p>
*
* @return The <em>rollback</em> flag for the current test.
*/
protected boolean isRollback() {
return isDefaultRollback();
}
@@ -174,7 +164,6 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
* transactional execution.
*/
protected void preventTransaction() {
this.transactionDefinition = null;
}
@@ -182,28 +171,23 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
* Call this method in an overridden {@link #runBare()} method to override
* the transaction attributes that will be used, so that {@link #setUp()}
* and {@link #tearDown()} behavior is modified.
*
* @param customDefinition the custom transaction definition
*/
protected void setTransactionDefinition(final TransactionDefinition customDefinition) {
protected void setTransactionDefinition(TransactionDefinition customDefinition) {
this.transactionDefinition = customDefinition;
}
/**
* This implementation creates a transaction before test execution.
* <p>
* Override {@link #onSetUpBeforeTransaction()} and/or
* <p>Override {@link #onSetUpBeforeTransaction()} and/or
* {@link #onSetUpInTransaction()} to add custom set-up behavior for
* transactional execution. Alternatively, override this method for general
* set-up behavior, calling <code>super.onSetUp()</code> as part of your
* method implementation.
*
* @throws Exception simply let any exception propagate
* @see #onTearDown()
*/
protected void onSetUp() throws Exception {
this.complete = !this.isRollback();
if (this.transactionManager == null) {
@@ -231,52 +215,42 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
* this class. Only invoked if there <i>is</i> a transaction: that is, if
* {@link #preventTransaction()} has not been invoked in an overridden
* {@link #runTest()} method.
*
* @throws Exception simply let any exception propagate
*/
protected void onSetUpBeforeTransaction() throws Exception {
}
/**
* Subclasses can override this method to perform any setup operations, such
* as populating a database table, <i>within</i> the transaction created by
* this class.
* <p>
* <b>NB:</b> Not called if there is no transaction management, due to no
* <p><b>NB:</b> Not called if there is no transaction management, due to no
* transaction manager being provided in the context.
* <p>
* If any {@link Throwable} is thrown, the transaction that has been started
* <p>If any {@link Throwable} is thrown, the transaction that has been started
* prior to the execution of this method will be
* {@link #endTransaction() ended} (or rather an attempt will be made to
* {@link #endTransaction() end it gracefully}); The offending
* {@link Throwable} will then be rethrown.
*
* @throws Exception simply let any exception propagate
*/
protected void onSetUpInTransaction() throws Exception {
}
/**
* This implementation ends the transaction after test execution.
* <p>
* Override {@link #onTearDownInTransaction()} and/or
* <p>Override {@link #onTearDownInTransaction()} and/or
* {@link #onTearDownAfterTransaction()} to add custom tear-down behavior
* for transactional execution. Alternatively, override this method for
* general tear-down behavior, calling <code>super.onTearDown()</code> as
* part of your method implementation.
* <p>
* Note that {@link #onTearDownInTransaction()} will only be called if a
* <p>Note that {@link #onTearDownInTransaction()} will only be called if a
* transaction is still active at the time of the test shutdown. In
* particular, it will <i>not</i> be called if the transaction has been
* completed with an explicit {@link #endTransaction()} call before.
*
* @throws Exception simply let any exception propagate
* @see #onSetUp()
*/
protected void onTearDown() throws Exception {
// Call onTearDownInTransaction and end transaction if the transaction
// is still active.
if (this.transactionStatus != null && !this.transactionStatus.isCompleted()) {
@@ -287,6 +261,7 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
endTransaction();
}
}
// Call onTearDownAfterTransaction if there was at least one
// transaction, even if it has been completed early through an
// endTransaction() call.
@@ -300,35 +275,28 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
* transaction is <i>still active</i> at this point, so any changes made in
* the transaction will still be visible. However, there is no need to clean
* up the database, as a rollback will follow automatically.
* <p>
* <b>NB:</b> Not called if there is no actual transaction, for example due
* <p><b>NB:</b> Not called if there is no actual transaction, for example due
* to no transaction manager being provided in the application context.
*
* @throws Exception simply let any exception propagate
*/
protected void onTearDownInTransaction() throws Exception {
}
/**
* Subclasses can override this method to perform cleanup after a
* transaction here. At this point, the transaction is <i>not active anymore</i>.
*
* @throws Exception simply let any exception propagate
*/
protected void onTearDownAfterTransaction() throws Exception {
}
/**
* Cause the transaction to commit for this test method, even if the test
* method is configured to {@link #isRollback() rollback}.
*
* @throws IllegalStateException if the operation cannot be set to complete
* as no transaction manager was provided
* as no transaction manager was provided
*/
protected void setComplete() {
if (this.transactionManager == null) {
throw new IllegalStateException("No transaction manager set");
}
@@ -338,17 +306,13 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
/**
* Immediately force a commit or rollback of the transaction, according to
* the <code>complete</code> and {@link #isRollback() rollback} flags.
* <p>
* Can be used to explicitly let the transaction end early, for example to
* <p>Can be used to explicitly let the transaction end early, for example to
* check whether lazy associations of persistent objects work outside of a
* transaction (that is, have been initialized properly).
*
* @see #setComplete()
*/
protected void endTransaction() {
final boolean commit = this.complete || !isRollback();
if (this.transactionStatus != null) {
try {
if (commit) {
@@ -371,11 +335,9 @@ public abstract class AbstractTransactionalSpringContextTests extends AbstractDe
* {@link #endTransaction()} has been called. {@link #setComplete()} can be
* used again in the new transaction. The fate of the new transaction, by
* default, will be the usual rollback.
*
* @throws TransactionException if starting the transaction failed
*/
protected void startNewTransaction() throws TransactionException {
if (this.transactionStatus != null) {
throw new IllegalStateException("Cannot start new transaction without ending existing transaction: "
+ "Invoke endTransaction() before startNewTransaction()");

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -16,9 +16,6 @@
package org.springframework.test;
import junit.framework.Assert;
import junit.framework.AssertionFailedError;
/**
* Simple method object encapsulation of the 'test-for-Exception' scenario (for JUnit).
*
@@ -77,11 +74,10 @@ import junit.framework.AssertionFailedError;
* }
* }</pre>
*
* Intended for use with JUnit 4 and TestNG (as of Spring 3.0).
* You might want to compare this class with the
* {@link junit.extensions.ExceptionTestCase} class.
*
* <p>Note: This class requires JDK 1.4 or higher.
*
* @author Rick Evans
* @author Juergen Hoeller
* @since 2.0
@@ -193,7 +189,7 @@ public abstract class AssertThrows {
* @see #getFailureMessage()
*/
protected void doFail() {
Assert.fail(createMessageForNoExceptionThrown());
throw new AssertionError(createMessageForNoExceptionThrown());
}
/**
@@ -203,7 +199,7 @@ public abstract class AssertThrows {
* @see #getFailureMessage()
*/
protected String createMessageForNoExceptionThrown() {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
sb.append("Should have thrown a [").append(this.getExpectedException()).append("]");
if (getFailureMessage() != null) {
sb.append(": ").append(getFailureMessage());
@@ -223,8 +219,8 @@ public abstract class AssertThrows {
*/
protected void checkExceptionExpectations(Exception actualException) {
if (!getExpectedException().isAssignableFrom(actualException.getClass())) {
AssertionFailedError error =
new AssertionFailedError(createMessageForWrongThrownExceptionType(actualException));
AssertionError error =
new AssertionError(createMessageForWrongThrownExceptionType(actualException));
error.initCause(actualException);
throw error;
}
@@ -237,7 +233,7 @@ public abstract class AssertThrows {
* @return the message for the given exception
*/
protected String createMessageForWrongThrownExceptionType(Exception actualException) {
StringBuffer sb = new StringBuffer();
StringBuilder sb = new StringBuilder();
sb.append("Was expecting a [").append(getExpectedException().getName());
sb.append("] to be thrown, but instead a [").append(actualException.getClass().getName());
sb.append("] was thrown.");

View File

@@ -32,7 +32,10 @@ import org.apache.commons.logging.LogFactory;
* @author Rod Johnson
* @since 2.0
* @see #isDisabledInThisEnvironment
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class ConditionalTestCase extends TestCase {
private static int disabledTestCount;
@@ -78,7 +81,6 @@ public abstract class ConditionalTestCase extends TestCase {
/**
* Should this test run?
*
* @param testMethodName name of the test method
* @return whether the test should execute in the current environment
*/
@@ -88,7 +90,6 @@ public abstract class ConditionalTestCase extends TestCase {
/**
* Record a disabled test.
*
* @return the current disabled test count
*/
protected int recordDisabled() {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2007 the original author or authors.
* 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.
@@ -33,14 +33,13 @@ public class JdbcTestUtils {
/**
* Read a script from the LineNumberReaded and build a String containing the lines.
*
* @param lineNumberReader the <code>LineNumberReader</> containing the script to be processed
* @return <code>String</code> containing the script lines
* @throws IOException
*/
public static String readScript(LineNumberReader lineNumberReader) throws IOException {
String currentStatement = lineNumberReader.readLine();
StringBuffer scriptBuilder = new StringBuffer();
StringBuilder scriptBuilder = new StringBuilder();
while (currentStatement != null) {
if (StringUtils.hasText(currentStatement)) {
if (scriptBuilder.length() > 0) {
@@ -55,17 +54,15 @@ public class JdbcTestUtils {
/**
* Does the provided SQL script contain the specified delimiter?
*
* @param script the SQL script
* @param delim charecter delimiting each statement - typically a ';' character
*/
public static boolean containsSqlScriptDelimiters(String script, char delim) {
boolean inLiteral = false;
char[] content = script.toCharArray();
for (int i = 0; i < script.length(); i++) {
if (content[i] == '\'') {
inLiteral = inLiteral ? false : true;
inLiteral = !inLiteral;
}
if (content[i] == delim && !inLiteral) {
return true;
@@ -81,19 +78,18 @@ public class JdbcTestUtils {
* @param delim charecter delimiting each statement - typically a ';' character
* @param statements the List that will contain the individual statements
*/
public static void splitSqlScript(String script, char delim, List statements) {
StringBuffer sb = new StringBuffer();
public static void splitSqlScript(String script, char delim, List<String> statements) {
StringBuilder sb = new StringBuilder();
boolean inLiteral = false;
char[] content = script.toCharArray();
for (int i = 0; i < script.length(); i++) {
if (content[i] == '\'') {
inLiteral = inLiteral ? false : true;
inLiteral = !inLiteral;
}
if (content[i] == delim && !inLiteral) {
if (sb.length() > 0) {
statements.add(sb.toString());
sb = new StringBuffer();
sb = new StringBuilder();
}
}
else {

View File

@@ -18,7 +18,6 @@ package org.springframework.test.jdbc;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
@@ -31,7 +30,6 @@ import org.springframework.core.io.support.EncodedResource;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DataAccessResourceFailureException;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.util.StringUtils;
/**
* A Java-5-based collection of JDBC related utility functions intended to
@@ -65,11 +63,11 @@ public abstract class SimpleJdbcTestUtils {
*/
public static int deleteFromTables(SimpleJdbcTemplate simpleJdbcTemplate, String... tableNames) {
int totalRowCount = 0;
for (int i = 0; i < tableNames.length; i++) {
int rowCount = simpleJdbcTemplate.update("DELETE FROM " + tableNames[i]);
for (String tableName : tableNames) {
int rowCount = simpleJdbcTemplate.update("DELETE FROM " + tableName);
totalRowCount += rowCount;
if (logger.isInfoEnabled()) {
logger.info("Deleted " + rowCount + " rows from table " + tableNames[i]);
logger.info("Deleted " + rowCount + " rows from table " + tableName);
}
}
return totalRowCount;
@@ -145,8 +143,7 @@ public abstract class SimpleJdbcTestUtils {
delimiter = '\n';
}
JdbcTestUtils.splitSqlScript(script, delimiter, statements);
for (Iterator<String> itr = statements.iterator(); itr.hasNext();) {
String statement = itr.next();
for (String statement : statements) {
try {
int rowsAffected = simpleJdbcTemplate.update(statement);
if (logger.isDebugEnabled()) {

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -26,16 +26,12 @@ import junit.framework.TestCase;
import org.springframework.web.servlet.ModelAndView;
/**
* <p>
* Convenient JUnit 3.8 base class for tests dealing with Spring Web MVC
* {@link org.springframework.web.servlet.ModelAndView ModelAndView} objects.
* </p>
* <p>
* All <code>assert*()</code> methods throw {@link AssertionFailedError}s.
* </p>
* <p>
* Consider the use of {@link ModelAndViewAssert} with JUnit 4 and TestNG.
* </p>
*
* <p>All <code>assert*()</code> methods throw {@link AssertionFailedError}s.
*
* <p>Consider the use of {@link ModelAndViewAssert} with JUnit 4 and TestNG.
*
* @author Alef Arendsen
* @author Bram Smeets
@@ -43,14 +39,16 @@ import org.springframework.web.servlet.ModelAndView;
* @since 2.0
* @see org.springframework.web.servlet.ModelAndView
* @see ModelAndViewAssert
* @deprecated as of Spring 3.0, in favor of using the listener-based test context framework
* ({@link org.springframework.test.context.junit38.AbstractJUnit38SpringContextTests})
*/
@Deprecated
public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Checks whether the model value under the given <code>modelName</code>
* exists and checks it type, based on the <code>expectedType</code>. If
* the model entry exists and the type matches, the model value is returned.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
@@ -58,7 +56,6 @@ public abstract class AbstractModelAndViewTests extends TestCase {
* @return the model value
*/
protected Object assertAndReturnModelAttributeOfType(ModelAndView mav, Object modelName, Class expectedType) {
try {
return ModelAndViewAssert.assertAndReturnModelAttributeOfType(mav, modelName, expectedType);
}
@@ -69,14 +66,12 @@ public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Compare each individual entry in a list, without first sorting the lists.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
* @param expectedList the expected list
*/
protected void assertCompareListModelAttribute(ModelAndView mav, Object modelName, List expectedList) {
try {
ModelAndViewAssert.assertCompareListModelAttribute(mav, modelName, expectedList);
}
@@ -87,13 +82,11 @@ public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Assert whether or not a model attribute is available.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
*/
protected void assertModelAttributeAvailable(ModelAndView mav, Object modelName) {
try {
ModelAndViewAssert.assertModelAttributeAvailable(mav, modelName);
}
@@ -105,14 +98,12 @@ public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Compare a given <code>expectedValue</code> to the value from the model
* bound under the given <code>modelName</code>.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
* @param expectedValue the model value
*/
protected void assertModelAttributeValue(ModelAndView mav, Object modelName, Object expectedValue) {
try {
ModelAndViewAssert.assertModelAttributeValue(mav, modelName, expectedValue);
}
@@ -124,12 +115,10 @@ public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Inspect the <code>expectedModel</code> to see if all elements in the
* model appear and are equal.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param expectedModel the expected model
*/
protected void assertModelAttributeValues(ModelAndView mav, Map expectedModel) {
try {
ModelAndViewAssert.assertModelAttributeValues(mav, expectedModel);
}
@@ -141,7 +130,6 @@ public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Compare each individual entry in a list after having sorted both lists
* (optionally using a comparator).
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
@@ -152,7 +140,6 @@ public abstract class AbstractModelAndViewTests extends TestCase {
*/
protected void assertSortAndCompareListModelAttribute(
ModelAndView mav, Object modelName, List expectedList, Comparator comparator) {
try {
ModelAndViewAssert.assertSortAndCompareListModelAttribute(mav, modelName, expectedList, comparator);
}
@@ -164,12 +151,10 @@ public abstract class AbstractModelAndViewTests extends TestCase {
/**
* Check to see if the view name in the ModelAndView matches the given
* <code>expectedName</code>.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param expectedName the name of the model value
*/
protected void assertViewName(ModelAndView mav, String expectedName) {
try {
ModelAndViewAssert.assertViewName(mav, expectedName);
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2007 the original author or authors.
* 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.
@@ -19,7 +19,6 @@ package org.springframework.test.web;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@@ -27,15 +26,12 @@ import java.util.Set;
import org.springframework.web.servlet.ModelAndView;
/**
* <p>
* A collection of assertions intended to simplify testing scenarios
* dealing with Spring Web MVC
* {@link org.springframework.web.servlet.ModelAndView ModelAndView} objects.
* Intended for use with JUnit 4 and TestNG.
* </p>
* <p>
*
* <p>Intended for use with JUnit 4 and TestNG.
* All <code>assert*()</code> methods throw {@link AssertionError}s.
* </p>
*
* @author Sam Brannen
* @author Alef Arendsen
@@ -49,29 +45,28 @@ public abstract class ModelAndViewAssert {
* Checks whether the model value under the given <code>modelName</code>
* exists and checks it type, based on the <code>expectedType</code>. If
* the model entry exists and the type matches, the model value is returned.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
* @param expectedType expected type of the model value
* @return the model value
*/
public static Object assertAndReturnModelAttributeOfType(ModelAndView mav, Object modelName, Class expectedType)
@SuppressWarnings("unchecked")
public static <T> T assertAndReturnModelAttributeOfType(ModelAndView mav, Object modelName, Class<T> expectedType)
throws AssertionError {
assertCondition(mav != null, "ModelAndView is null");
assertCondition(mav.getModel() != null, "Model is null");
final Object obj = mav.getModel().get(modelName);
Object obj = mav.getModel().get(modelName);
assertCondition(obj != null, "Model attribute with name '" + modelName + "' is null");
assertCondition(expectedType.isAssignableFrom(obj.getClass()), "Model attribute is not of expected type '"
+ expectedType.getName() + "' but rather of type '" + obj.getClass().getName() + "'");
return obj;
assertCondition(expectedType.isAssignableFrom(obj.getClass()), "Model attribute is not of expected type '" +
expectedType.getName() + "' but rather of type '" + obj.getClass().getName() + "'");
return (T) obj;
}
/**
* Compare each individual entry in a list, without first sorting the lists.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
@@ -82,101 +77,92 @@ public abstract class ModelAndViewAssert {
assertCondition(mav != null, "ModelAndView is null");
List modelList = (List) assertAndReturnModelAttributeOfType(mav, modelName, List.class);
assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size()
+ "' while size of expected list is '" + expectedList.size() + "'");
assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName
+ "' is not equal to the expected list.");
assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() +
"' while size of expected list is '" + expectedList.size() + "'");
assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName +
"' is not equal to the expected list.");
}
/**
* Assert whether or not a model attribute is available.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
*/
public static void assertModelAttributeAvailable(ModelAndView mav, Object modelName) throws AssertionError {
assertCondition(mav != null, "ModelAndView is null");
assertCondition(mav.getModel() != null, "Model is null");
assertCondition(mav.getModel().containsKey(modelName), "Model attribute with name '" + modelName
+ "' is not available");
assertCondition(mav.getModel().containsKey(modelName), "Model attribute with name '" + modelName +
"' is not available");
}
/**
* Compare a given <code>expectedValue</code> to the value from the model
* bound under the given <code>modelName</code>.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
* @param expectedValue the model value
*/
public static void assertModelAttributeValue(ModelAndView mav, Object modelName, Object expectedValue)
throws AssertionError {
public static void assertModelAttributeValue(ModelAndView mav, Object modelName, Object expectedValue) {
assertCondition(mav != null, "ModelAndView is null");
Object modelValue = assertAndReturnModelAttributeOfType(mav, modelName, Object.class);
assertCondition(modelValue.equals(expectedValue), "Model value with name '" + modelName
+ "' is not the same as the expected value which was '" + expectedValue + "'");
assertCondition(modelValue.equals(expectedValue), "Model value with name '" + modelName +
"' is not the same as the expected value which was '" + expectedValue + "'");
}
/**
* Inspect the <code>expectedModel</code> to see if all elements in the
* model appear and are equal.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param expectedModel the expected model
*/
public static void assertModelAttributeValues(ModelAndView mav, Map expectedModel) throws AssertionError {
public static void assertModelAttributeValues(ModelAndView mav, Map<String, Object> expectedModel) {
assertCondition(mav != null, "ModelAndView is null");
assertCondition(mav.getModel() != null, "Model is null");
if (!mav.getModel().keySet().equals(expectedModel.keySet())) {
StringBuffer buf = new StringBuffer("Keyset of expected model does not match.\n");
appendNonMatchingSetsErrorMessage(expectedModel.keySet(), mav.getModel().keySet(), buf);
fail(buf.toString());
StringBuilder sb = new StringBuilder("Keyset of expected model does not match.\n");
appendNonMatchingSetsErrorMessage(expectedModel.keySet(), mav.getModel().keySet(), sb);
fail(sb.toString());
}
StringBuffer buf = new StringBuffer();
Iterator it = mav.getModel().keySet().iterator();
while (it.hasNext()) {
Object modelName = it.next();
StringBuilder sb = new StringBuilder();
for (String modelName : mav.getModel().keySet()) {
Object assertionValue = expectedModel.get(modelName);
Object mavValue = mav.getModel().get(modelName);
if (!assertionValue.equals(mavValue)) {
buf.append("Value under name '" + modelName + "' differs, should have been '" + assertionValue
+ "' but was '" + mavValue + "'\n");
sb.append("Value under name '").append(modelName).append("' differs, should have been '")
.append(assertionValue).append("' but was '").append(mavValue).append("'\n");
}
}
if (buf.length() != 0) {
buf.insert(0, "Values of expected model do not match.\n");
fail(buf.toString());
if (sb.length() != 0) {
sb.insert(0, "Values of expected model do not match.\n");
fail(sb.toString());
}
}
/**
* Compare each individual entry in a list after having sorted both lists
* (optionally using a comparator).
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param modelName name of the object to add to the model (never
* <code>null</code>)
* @param modelName name of the object to add to the model
* (never <code>null</code>)
* @param expectedList the expected list
* @param comparator the comparator to use (may be <code>null</code>). If
* not specifying the comparator, both lists will be sorted not using
* @param comparator the comparator to use (may be <code>null</code>).
* If not specifying the comparator, both lists will be sorted not using
* any comparator.
*/
@SuppressWarnings("unchecked")
public static void assertSortAndCompareListModelAttribute(
ModelAndView mav, Object modelName, List expectedList, Comparator comparator) throws AssertionError {
ModelAndView mav, Object modelName, List expectedList, Comparator comparator) {
assertCondition(mav != null, "ModelAndView is null");
List modelList = (List) assertAndReturnModelAttributeOfType(mav, modelName, List.class);
List modelList = assertAndReturnModelAttributeOfType(mav, modelName, List.class);
assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size()
+ "' while size of expected list is '" + expectedList.size() + "'");
assertCondition(expectedList.size() == modelList.size(), "Size of model list is '" + modelList.size() +
"' while size of expected list is '" + expectedList.size() + "'");
if (comparator != null) {
Collections.sort(modelList, comparator);
@@ -187,34 +173,30 @@ public abstract class ModelAndViewAssert {
Collections.sort(expectedList);
}
assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName
+ "' is not equal to the expected list.");
assertCondition(expectedList.equals(modelList), "List in model under name '" + modelName +
"' is not equal to the expected list.");
}
/**
* Check to see if the view name in the ModelAndView matches the given
* <code>expectedName</code>.
*
* @param mav ModelAndView to test against (never <code>null</code>)
* @param expectedName the name of the model value
*/
public static void assertViewName(ModelAndView mav, String expectedName) throws AssertionError {
public static void assertViewName(ModelAndView mav, String expectedName) {
assertCondition(mav != null, "ModelAndView is null");
assertCondition(expectedName.equals(mav.getViewName()), "View name is not equal to '" + expectedName
+ "' but was '" + mav.getViewName() + "'");
assertCondition(expectedName.equals(mav.getViewName()), "View name is not equal to '" + expectedName +
"' but was '" + mav.getViewName() + "'");
}
/**
* Fails by throwing an <code>AssertionError</code> with the supplied
* <code>message</code>.
*
* @param message the exception message to use
* @see #assertCondition(boolean,String)
*/
private static void fail(String message) throws AssertionError {
private static void fail(String message) {
throw new AssertionError(message);
}
@@ -222,47 +204,39 @@ public abstract class ModelAndViewAssert {
* Assert the provided boolean <code>condition</code>, throwing
* <code>AssertionError</code> with the supplied <code>message</code> if
* the test result is <code>false</code>.
*
* @param condition a boolean expression
* @param message the exception message to use if the assertion fails
* @throws AssertionError if condition is <code>false</code>
* @see #fail(String)
*/
private static void assertCondition(boolean condition, String message) throws AssertionError {
private static void assertCondition(boolean condition, String message) {
if (!condition) {
fail(message);
}
}
private static void appendNonMatchingSetsErrorMessage(Set assertionSet, Set incorrectSet, StringBuffer buf) {
Set tempSet = new HashSet();
private static void appendNonMatchingSetsErrorMessage(Set<String> assertionSet, Set<String> incorrectSet, StringBuilder buf) {
Set<String> tempSet = new HashSet<String>();
tempSet.addAll(incorrectSet);
tempSet.removeAll(assertionSet);
if (tempSet.size() > 0) {
buf.append("Set has too many elements:\n");
Iterator it = tempSet.iterator();
while (it.hasNext()) {
Object o = it.next();
for (Object element : tempSet) {
buf.append('-');
buf.append(o.toString());
buf.append(element);
buf.append('\n');
}
}
tempSet = new HashSet();
tempSet = new HashSet<String>();
tempSet.addAll(assertionSet);
tempSet.removeAll(incorrectSet);
if (tempSet.size() > 0) {
buf.append("Set is missing elements:\n");
Iterator it = tempSet.iterator();
while (it.hasNext()) {
Object o = it.next();
for (Object element : tempSet) {
buf.append('-');
buf.append(o.toString());
buf.append(element);
buf.append('\n');
}
}