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

@@ -17,7 +17,6 @@
package org.springframework.web.bind;
import java.lang.reflect.Array;
import java.util.Iterator;
import java.util.Map;
import org.springframework.beans.MutablePropertyValues;
@@ -165,8 +164,7 @@ public class WebDataBinder extends DataBinder {
if (getFieldMarkerPrefix() != null) {
String fieldMarkerPrefix = getFieldMarkerPrefix();
PropertyValue[] pvArray = mpvs.getPropertyValues();
for (int i = 0; i < pvArray.length; i++) {
PropertyValue pv = pvArray[i];
for (PropertyValue pv : pvArray) {
if (pv.getName().startsWith(fieldMarkerPrefix)) {
String field = pv.getName().substring(fieldMarkerPrefix.length());
if (getPropertyAccessor().isWritableProperty(field) && !mpvs.contains(field)) {
@@ -214,11 +212,10 @@ public class WebDataBinder extends DataBinder {
* @see org.springframework.web.multipart.MultipartFile
* @see #setBindEmptyMultipartFiles
*/
protected void bindMultipartFiles(Map multipartFiles, MutablePropertyValues mpvs) {
for (Iterator it = multipartFiles.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String key = (String) entry.getKey();
MultipartFile value = (MultipartFile) entry.getValue();
protected void bindMultipartFiles(Map<String, MultipartFile> multipartFiles, MutablePropertyValues mpvs) {
for (Map.Entry<String, MultipartFile> entry : multipartFiles.entrySet()) {
String key = entry.getKey();
MultipartFile value = entry.getValue();
if (isBindEmptyMultipartFiles() || !value.isEmpty()) {
mpvs.addPropertyValue(key, value);
}

View File

@@ -37,7 +37,7 @@ public interface MultipartRequest {
* original file names.
* @return the names of the files
*/
Iterator getFileNames();
Iterator<String> getFileNames();
/**
* Return the contents plus description of an uploaded file in this request,
@@ -53,6 +53,6 @@ public interface MultipartRequest {
* {@link org.springframework.web.multipart.MultipartFile} objects as values
* @see MultipartFile
*/
Map getFileMap();
Map<String, MultipartFile> getFileMap();
}

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,7 +20,6 @@ import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@@ -34,6 +33,7 @@ import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.util.WebUtils;
/**
@@ -212,13 +212,12 @@ public abstract class CommonsFileUploadSupport {
* @return the Spring MultipartParsingResult
* @see CommonsMultipartFile#CommonsMultipartFile(org.apache.commons.fileupload.FileItem)
*/
protected MultipartParsingResult parseFileItems(List fileItems, String encoding) {
Map multipartFiles = new HashMap();
Map multipartParameters = new HashMap();
protected MultipartParsingResult parseFileItems(List<FileItem> fileItems, String encoding) {
Map<String, MultipartFile> multipartFiles = new HashMap<String, MultipartFile>();
Map<String, String[]> multipartParameters = new HashMap<String, String[]>();
// Extract multipart files and multipart parameters.
for (Iterator it = fileItems.iterator(); it.hasNext();) {
FileItem fileItem = (FileItem) it.next();
for (FileItem fileItem : fileItems) {
if (fileItem.isFormField()) {
String value = null;
if (encoding != null) {
@@ -236,10 +235,10 @@ public abstract class CommonsFileUploadSupport {
else {
value = fileItem.getString();
}
String[] curParam = (String[]) multipartParameters.get(fileItem.getFieldName());
String[] curParam = multipartParameters.get(fileItem.getFieldName());
if (curParam == null) {
// simple form field
multipartParameters.put(fileItem.getFieldName(), new String[] { value });
multipartParameters.put(fileItem.getFieldName(), new String[] {value});
}
else {
// array of simple form fields
@@ -251,8 +250,8 @@ public abstract class CommonsFileUploadSupport {
// multipart file field
CommonsMultipartFile file = new CommonsMultipartFile(fileItem);
if (multipartFiles.put(file.getName(), file) != null) {
throw new MultipartException(
"Multiple files for field name [" + file.getName() + "] found - not supported by MultipartResolver");
throw new MultipartException("Multiple files for field name [" + file.getName() +
"] found - not supported by MultipartResolver");
}
if (logger.isDebugEnabled()) {
logger.debug("Found multipart file [" + file.getName() + "] of size " + file.getSize() +
@@ -271,14 +270,16 @@ public abstract class CommonsFileUploadSupport {
* @param multipartFiles Collection of MultipartFile instances
* @see org.apache.commons.fileupload.FileItem#delete()
*/
protected void cleanupFileItems(Collection multipartFiles) {
for (Iterator it = multipartFiles.iterator(); it.hasNext();) {
CommonsMultipartFile file = (CommonsMultipartFile) it.next();
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up multipart file [" + file.getName() + "] with original filename [" +
file.getOriginalFilename() + "], stored " + file.getStorageDescription());
protected void cleanupFileItems(Collection<MultipartFile> multipartFiles) {
for (MultipartFile file : multipartFiles) {
if (file instanceof CommonsMultipartFile) {
CommonsMultipartFile cmf = (CommonsMultipartFile) file;
cmf.getFileItem().delete();
if (logger.isDebugEnabled()) {
logger.debug("Cleaning up multipart file [" + cmf.getName() + "] with original filename [" +
cmf.getOriginalFilename() + "], stored " + cmf.getStorageDescription());
}
}
file.getFileItem().delete();
}
}
@@ -289,31 +290,31 @@ public abstract class CommonsFileUploadSupport {
*/
protected static class MultipartParsingResult {
private final Map multipartFiles;
private final Map<String, MultipartFile> multipartFiles;
private final Map multipartParameters;
private final Map<String, String[]> multipartParameters;
/**
* Create a new MultipartParsingResult.
* @param multipartFiles Map of field name to MultipartFile instance
* @param mpFiles Map of field name to MultipartFile instance
* @param multipartParameters Map of field name to form field String value
*/
public MultipartParsingResult(Map multipartFiles, Map multipartParameters) {
this.multipartFiles = multipartFiles;
this.multipartParameters = multipartParameters;
public MultipartParsingResult(Map<String, MultipartFile> mpFiles, Map<String, String[]> mpParams) {
this.multipartFiles = mpFiles;
this.multipartParameters = mpParams;
}
/**
* Return the multipart files as Map of field name to MultipartFile instance.
*/
public Map getMultipartFiles() {
public Map<String, MultipartFile> getMultipartFiles() {
return this.multipartFiles;
}
/**
* Return the multipart parameters as Map of field name to form field String value.
*/
public Map getMultipartParameters() {
public Map<String, String[]> getMultipartParameters() {
return this.multipartParameters;
}
}

View File

@@ -24,6 +24,7 @@ import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadBase;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.util.Assert;
@@ -118,12 +119,7 @@ public class CommonsMultipartResolver extends CommonsFileUploadSupport
public boolean isMultipart(HttpServletRequest request) {
if (request == null) {
return false;
}
else {
return ServletFileUpload.isMultipartContent(request);
}
return (request != null && ServletFileUpload.isMultipartContent(request));
}
public MultipartHttpServletRequest resolveMultipart(final HttpServletRequest request) throws MultipartException {
@@ -151,11 +147,12 @@ public class CommonsMultipartResolver extends CommonsFileUploadSupport
* @return the parsing result
* @throws MultipartException if multipart resolution failed.
*/
@SuppressWarnings("unchecked")
protected MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException {
String encoding = determineEncoding(request);
FileUpload fileUpload = prepareFileUpload(encoding);
try {
List fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
return parseFileItems(fileItems, encoding);
}
catch (FileUploadBase.SizeLimitExceededException ex) {

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 @@ import org.springframework.web.multipart.MultipartHttpServletRequest;
public abstract class AbstractMultipartHttpServletRequest extends HttpServletRequestWrapper
implements MultipartHttpServletRequest {
private Map multipartFiles;
private Map<String, MultipartFile> multipartFiles;
/**
@@ -48,15 +48,15 @@ public abstract class AbstractMultipartHttpServletRequest extends HttpServletReq
}
public Iterator getFileNames() {
public Iterator<String> getFileNames() {
return getMultipartFiles().keySet().iterator();
}
public MultipartFile getFile(String name) {
return (MultipartFile) getMultipartFiles().get(name);
return getMultipartFiles().get(name);
}
public Map getFileMap() {
public Map<String, MultipartFile> getFileMap() {
return getMultipartFiles();
}
@@ -65,7 +65,7 @@ public abstract class AbstractMultipartHttpServletRequest extends HttpServletReq
* Set a Map with parameter names as keys and MultipartFile objects as values.
* To be invoked by subclasses on initialization.
*/
protected final void setMultipartFiles(Map multipartFiles) {
protected final void setMultipartFiles(Map<String, MultipartFile> multipartFiles) {
this.multipartFiles = Collections.unmodifiableMap(multipartFiles);
}
@@ -74,7 +74,7 @@ public abstract class AbstractMultipartHttpServletRequest extends HttpServletReq
* lazily initializing it if necessary.
* @see #initializeMultipart()
*/
protected Map getMultipartFiles() {
protected Map<String, MultipartFile> getMultipartFiles() {
if (this.multipartFiles == null) {
initializeMultipart();
}

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.
@@ -22,9 +22,10 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
/**
* Default implementation of the
* {@link org.springframework.web.multipart.MultipartHttpServletRequest}
@@ -37,22 +38,22 @@ import javax.servlet.http.HttpServletRequest;
*/
public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {
private Map multipartParameters;
private Map<String, String[]> multipartParameters;
/**
* Wrap the given HttpServletRequest in a MultipartHttpServletRequest.
* @param request the servlet request to wrap
* @param multipartFiles a map of the multipart files
* @param multipartParameters a map of the parameters to expose,
* @param mpFiles a map of the multipart files
* @param mpParams a map of the parameters to expose,
* with Strings as keys and String arrays as values
*/
public DefaultMultipartHttpServletRequest(
HttpServletRequest request, Map multipartFiles, Map multipartParameters) {
HttpServletRequest request, Map<String, MultipartFile> mpFiles, Map<String, String[]> mpParams) {
super(request);
setMultipartFiles(multipartFiles);
setMultipartParameters(multipartParameters);
setMultipartFiles(mpFiles);
setMultipartParameters(mpParams);
}
/**
@@ -65,11 +66,11 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer
@Override
public Enumeration getParameterNames() {
Set paramNames = new HashSet();
public Enumeration<String> getParameterNames() {
Set<String> paramNames = new HashSet<String>();
Enumeration paramEnum = super.getParameterNames();
while (paramEnum.hasMoreElements()) {
paramNames.add(paramEnum.nextElement());
paramNames.add((String) paramEnum.nextElement());
}
paramNames.addAll(getMultipartParameters().keySet());
return Collections.enumeration(paramNames);
@@ -77,7 +78,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer
@Override
public String getParameter(String name) {
String[] values = (String[]) getMultipartParameters().get(name);
String[] values = getMultipartParameters().get(name);
if (values != null) {
return (values.length > 0 ? values[0] : null);
}
@@ -86,7 +87,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer
@Override
public String[] getParameterValues(String name) {
String[] values = (String[]) getMultipartParameters().get(name);
String[] values = getMultipartParameters().get(name);
if (values != null) {
return values;
}
@@ -94,8 +95,9 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer
}
@Override
public Map getParameterMap() {
Map paramMap = new HashMap();
@SuppressWarnings("unchecked")
public Map<String, String[]> getParameterMap() {
Map<String, String[]> paramMap = new HashMap<String, String[]>();
paramMap.putAll(super.getParameterMap());
paramMap.putAll(getMultipartParameters());
return paramMap;
@@ -106,7 +108,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer
* Set a Map with parameter names as keys and String array objects as values.
* To be invoked by subclasses on initialization.
*/
protected final void setMultipartParameters(Map multipartParameters) {
protected final void setMultipartParameters(Map<String, String[]> multipartParameters) {
this.multipartParameters = multipartParameters;
}
@@ -115,7 +117,7 @@ public class DefaultMultipartHttpServletRequest extends AbstractMultipartHttpSer
* lazily initializing it if necessary.
* @see #initializeMultipart()
*/
protected Map getMultipartParameters() {
protected Map<String, String[]> getMultipartParameters() {
if (this.multipartParameters == null) {
initializeMultipart();
}

View File

@@ -1101,9 +1101,8 @@ public class DispatcherServlet extends FrameworkServlet {
// Check registerer HandlerExceptionResolvers...
ModelAndView exMv = null;
for (Iterator it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
HandlerExceptionResolver resolver = (HandlerExceptionResolver) it.next();
exMv = resolver.resolveException(request, response, handler, ex);
for (Iterator<HandlerExceptionResolver> it = this.handlerExceptionResolvers.iterator(); exMv == null && it.hasNext();) {
exMv = it.next().resolveException(request, response, handler, ex);
}
if (exMv != null) {
if (logger.isDebugEnabled()) {
@@ -1191,7 +1190,8 @@ public class DispatcherServlet extends FrameworkServlet {
* (typically in case of problems creating an actual View object)
* @see ViewResolver#resolveViewName
*/
protected View resolveViewName(String viewName, Map model, Locale locale, HttpServletRequest request)
protected View resolveViewName(
String viewName, Map<String, Object> model, Locale locale, HttpServletRequest request)
throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {

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.
@@ -92,7 +92,7 @@ public class ModelAndView {
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(String viewName, Map model) {
public ModelAndView(String viewName, Map<String, ?> model) {
this.view = viewName;
if (model != null) {
getModelMap().addAllAttributes(model);
@@ -109,7 +109,7 @@ public class ModelAndView {
* (Objects). Model entries may not be <code>null</code>, but the
* model Map may be <code>null</code> if there is no model data.
*/
public ModelAndView(View view, Map model) {
public ModelAndView(View view, Map<String, ?> model) {
this.view = view;
if (model != null) {
getModelMap().addAllAttributes(model);
@@ -194,7 +194,7 @@ public class ModelAndView {
* Return the model map. May return <code>null</code>.
* Called by DispatcherServlet for evaluation of the model.
*/
protected Map getModelInternal() {
protected Map<String, Object> getModelInternal() {
return this.model;
}
@@ -212,7 +212,7 @@ public class ModelAndView {
* Return the model map. Never returns <code>null</code>.
* To be called by application code for modifying the model.
*/
public Map getModel() {
public Map<String, Object> getModel() {
return getModelMap();
}
@@ -246,7 +246,7 @@ public class ModelAndView {
* @see ModelMap#addAllAttributes(Map)
* @see #getModelMap()
*/
public ModelAndView addAllObjects(Map modelMap) {
public ModelAndView addAllObjects(Map<String, ?> modelMap) {
getModelMap().addAllAttributes(modelMap);
return this;
}
@@ -291,14 +291,14 @@ public class ModelAndView {
*/
@Override
public String toString() {
StringBuffer buf = new StringBuffer("ModelAndView: ");
StringBuilder sb = new StringBuilder("ModelAndView: ");
if (isReference()) {
buf.append("reference to view with name '").append(this.view).append("'");
sb.append("reference to view with name '").append(this.view).append("'");
}
else {
buf.append("materialized View is [").append(this.view).append(']');
sb.append("materialized View is [").append(this.view).append(']');
}
buf.append("; model is ").append(this.model);
return buf.toString();
sb.append("; model is ").append(this.model);
return sb.toString();
}
}

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2002-2005 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.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -63,6 +63,6 @@ public interface View {
* @param response HTTP response we are building
* @throws Exception if rendering failed
*/
void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception;
void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception;
}

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.
@@ -104,12 +104,13 @@ public class ViewRendererServlet extends HttpServlet {
* @throws Exception in case of any kind of processing failure
* @see org.springframework.web.servlet.View#render
*/
@SuppressWarnings("unchecked")
protected void renderView(HttpServletRequest request, HttpServletResponse response) throws Exception {
View view = (View) request.getAttribute(VIEW_ATTRIBUTE);
if (view == null) {
throw new ServletException("Could not complete render request: View is null");
}
Map model = (Map) request.getAttribute(MODEL_ATTRIBUTE);
Map<String, Object> model = (Map<String, Object>) request.getAttribute(MODEL_ATTRIBUTE);
view.render(model, request, response);
}

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,11 +17,11 @@
package org.springframework.web.servlet.handler;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import org.springframework.beans.BeansException;
import org.springframework.util.CollectionUtils;
/**
* Implementation of the {@link org.springframework.web.servlet.HandlerMapping}
@@ -55,7 +55,7 @@ import org.springframework.beans.BeansException;
*/
public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
private final Map urlMap = new HashMap();
private final Map<String, Object> urlMap = new HashMap<String, Object>();
/**
@@ -67,7 +67,7 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
* @see #setUrlMap
*/
public void setMappings(Properties mappings) {
this.urlMap.putAll(mappings);
CollectionUtils.mergePropertiesIntoMap(mappings, this.urlMap);
}
/**
@@ -78,7 +78,7 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
* @param urlMap map with URLs as keys and beans as values
* @see #setMappings
*/
public void setUrlMap(Map urlMap) {
public void setUrlMap(Map<String, Object> urlMap) {
this.urlMap.putAll(urlMap);
}
@@ -110,15 +110,14 @@ public class SimpleUrlHandlerMapping extends AbstractUrlHandlerMapping {
* @throws BeansException if a handler couldn't be registered
* @throws IllegalStateException if there is a conflicting handler registered
*/
protected void registerHandlers(Map urlMap) throws BeansException {
protected void registerHandlers(Map<String, Object> urlMap) throws BeansException {
if (urlMap.isEmpty()) {
logger.warn("Neither 'urlMap' nor 'mappings' set on SimpleUrlHandlerMapping");
}
else {
Iterator it = urlMap.keySet().iterator();
while (it.hasNext()) {
String url = (String) it.next();
Object handler = urlMap.get(url);
for (Map.Entry<String, Object> entry : urlMap.entrySet()) {
String url = entry.getKey();
Object handler = entry.getValue();
// Prepend with slash if not already present.
if (!url.startsWith("/")) {
url = "/" + url;

View File

@@ -47,7 +47,9 @@ import org.springframework.web.servlet.ModelAndView;
* @see #setCommandClass
* @see #setCommandName
* @see #setValidator
* @deprecated as of Spring 3.0, in favor of annotated controllers
*/
@Deprecated
public abstract class AbstractCommandController extends BaseCommandController {
/**

View File

@@ -167,7 +167,9 @@ import org.springframework.web.servlet.ModelAndView;
* @see #processFormSubmission
* @see SimpleFormController
* @see AbstractWizardFormController
* @deprecated as of Spring 3.0, in favor of annotated controllers
*/
@Deprecated
public abstract class AbstractFormController extends BaseCommandController {
private boolean bindOnNewForm = false;

View File

@@ -73,7 +73,9 @@ import org.springframework.web.util.WebUtils;
* @see #validatePage
* @see #processFinish
* @see #processCancel
* @deprecated as of Spring 3.0, in favor of annotated controllers
*/
@Deprecated
public abstract class AbstractWizardFormController extends AbstractFormController {
/**

View File

@@ -131,7 +131,9 @@ import org.springframework.web.context.request.ServletWebRequest;
*
* @author Rod Johnson
* @author Juergen Hoeller
* @deprecated as of Spring 3.0, in favor of annotated controllers
*/
@Deprecated
public abstract class BaseCommandController extends AbstractController {
/** Default command name used for binding command objects: "command" */

View File

@@ -57,7 +57,9 @@ import org.springframework.web.util.WebUtils;
* @see #setCancelView
* @see #isCancelRequest(javax.servlet.http.HttpServletRequest)
* @see #onCancel(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, Object)
* @deprecated as of Spring 3.0, in favor of annotated controllers
*/
@Deprecated
public class CancellableFormController extends SimpleFormController {
/**

View File

@@ -97,7 +97,9 @@ import org.springframework.web.servlet.ModelAndView;
* @author Juergen Hoeller
* @author Rob Harrop
* @since 05.05.2003
* @deprecated as of Spring 3.0, in favor of annotated controllers
*/
@Deprecated
public class SimpleFormController extends AbstractFormController {
private String formView;

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,11 +16,10 @@
package org.springframework.web.servlet.mvc;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -50,7 +49,7 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
private UrlPathHelper urlPathHelper = new UrlPathHelper();
private Map cacheMappings = new HashMap();
private Map<String, Integer> cacheMappings = new HashMap<String, Integer>();
private PathMatcher pathMatcher = new AntPathMatcher();
@@ -111,8 +110,9 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
*/
public void setCacheMappings(Properties cacheMappings) {
this.cacheMappings.clear();
for (Iterator it = cacheMappings.keySet().iterator(); it.hasNext();) {
String path = (String) it.next();
Enumeration propNames = cacheMappings.propertyNames();
while (propNames.hasMoreElements()) {
String path = (String) propNames.nextElement();
this.cacheMappings.put(path, Integer.valueOf(cacheMappings.getProperty(path)));
}
}
@@ -143,7 +143,7 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
if (logger.isDebugEnabled()) {
logger.debug("Applying " + cacheSeconds + " cache seconds to [" + lookupPath + "]");
}
checkAndPrepare(request, response, cacheSeconds.intValue(), handler instanceof LastModified);
checkAndPrepare(request, response, cacheSeconds, handler instanceof LastModified);
}
else {
if (logger.isDebugEnabled()) {
@@ -166,13 +166,12 @@ public class WebContentInterceptor extends WebContentGenerator implements Handle
*/
protected Integer lookupCacheSeconds(String urlPath) {
// direct match?
Integer cacheSeconds = (Integer) this.cacheMappings.get(urlPath);
Integer cacheSeconds = this.cacheMappings.get(urlPath);
if (cacheSeconds == null) {
// pattern match?
for (Iterator it = this.cacheMappings.keySet().iterator(); it.hasNext();) {
String registeredPath = (String) it.next();
for (String registeredPath : this.cacheMappings.keySet()) {
if (this.pathMatcher.match(registeredPath, urlPath)) {
cacheSeconds = (Integer) this.cacheMappings.get(registeredPath);
cacheSeconds = this.cacheMappings.get(registeredPath);
}
}
}

View File

@@ -24,10 +24,7 @@ import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.generic.GenericBeanFactoryAccessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.ReflectionUtils;
@@ -108,11 +105,7 @@ public class DefaultAnnotationHandlerMapping extends AbstractDetectingUrlHandler
protected String[] determineUrlsForHandler(String beanName) {
ApplicationContext context = getApplicationContext();
Class<?> handlerType = context.getType(beanName);
ListableBeanFactory bf = (context instanceof ConfigurableApplicationContext ?
((ConfigurableApplicationContext) context).getBeanFactory() : context);
GenericBeanFactoryAccessor bfa = new GenericBeanFactoryAccessor(bf);
RequestMapping mapping = bfa.findAnnotationOnBean(beanName, RequestMapping.class);
RequestMapping mapping = context.findAnnotationOnBean(beanName, RequestMapping.class);
if (mapping != null) {
// @RequestMapping found at type level
this.cachedMappings.put(handlerType, mapping);

View File

@@ -22,8 +22,6 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@@ -164,13 +162,13 @@ public class MultiActionController extends AbstractController implements LastMod
private WebBindingInitializer webBindingInitializer;
/** Handler methods, keyed by name */
private final Map handlerMethodMap = new HashMap();
private final Map<String, Method> handlerMethodMap = new HashMap<String, Method>();
/** LastModified methods, keyed by handler method name (without LAST_MODIFIED_SUFFIX) */
private final Map lastModifiedMethodMap = new HashMap();
private final Map<String, Method> lastModifiedMethodMap = new HashMap<String, Method>();
/** Methods, keyed by exception class */
private final Map exceptionHandlerMap = new HashMap();
private final Map<Class, Method> exceptionHandlerMap = new HashMap<Class, Method>();
/**
@@ -271,9 +269,8 @@ public class MultiActionController extends AbstractController implements LastMod
// Look at all methods in the subclass, trying to find
// methods that are validators according to our criteria
Method[] methods = delegate.getClass().getMethods();
for (int i = 0; i < methods.length; i++) {
for (Method method : methods) {
// We're looking for methods with given parameters.
Method method = methods[i];
if (isExceptionHandlerMethod(method)) {
registerExceptionHandlerMethod(method);
}
@@ -370,12 +367,12 @@ public class MultiActionController extends AbstractController implements LastMod
public long getLastModified(HttpServletRequest request) {
try {
String handlerMethodName = this.methodNameResolver.getHandlerMethodName(request);
Method lastModifiedMethod = (Method) this.lastModifiedMethodMap.get(handlerMethodName);
Method lastModifiedMethod = this.lastModifiedMethodMap.get(handlerMethodName);
if (lastModifiedMethod != null) {
try {
// Invoke the last-modified method...
Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, new Object[] {request});
return (wrappedLong != null ? wrappedLong.longValue() : -1);
Long wrappedLong = (Long) lastModifiedMethod.invoke(this.delegate, request);
return (wrappedLong != null ? wrappedLong : -1);
}
catch (Exception ex) {
// We encountered an error invoking the last-modified method.
@@ -443,14 +440,14 @@ public class MultiActionController extends AbstractController implements LastMod
protected final ModelAndView invokeNamedMethod(
String methodName, HttpServletRequest request, HttpServletResponse response) throws Exception {
Method method = (Method) this.handlerMethodMap.get(methodName);
Method method = this.handlerMethodMap.get(methodName);
if (method == null) {
throw new NoSuchRequestHandlingMethodException(methodName, getClass());
}
try {
Class[] paramTypes = method.getParameterTypes();
List params = new ArrayList(4);
List<Object> params = new ArrayList<Object>(4);
params.add(request);
params.add(response);
@@ -489,6 +486,7 @@ public class MultiActionController extends AbstractController implements LastMod
* <code>null</code> or an instance of {@link ModelAndView}. When returning a {@link Map},
* the {@link Map} instance is wrapped in a new {@link ModelAndView} instance.
*/
@SuppressWarnings("unchecked")
private ModelAndView massageReturnValueIfNecessary(Object returnValue) {
if (returnValue instanceof ModelAndView) {
return (ModelAndView) returnValue;
@@ -533,9 +531,9 @@ public class MultiActionController extends AbstractController implements LastMod
ServletRequestDataBinder binder = createBinder(request, command);
binder.bind(request);
if (this.validators != null) {
for (int i = 0; i < this.validators.length; i++) {
if (this.validators[i].supports(command.getClass())) {
ValidationUtils.invokeValidator(this.validators[i], command, binder.getBindingResult());
for (Validator validator : this.validators) {
if (validator.supports(command.getClass())) {
ValidationUtils.invokeValidator(validator, command, binder.getBindingResult());
}
}
}
@@ -594,16 +592,6 @@ public class MultiActionController extends AbstractController implements LastMod
if (this.webBindingInitializer != null) {
this.webBindingInitializer.initBinder(binder, new ServletWebRequest(request));
}
initBinder((ServletRequest) request, binder);
}
/**
* Initialize the given binder instance, for example with custom editors.
* @deprecated as of Spring 2.0:
* use <code>initBinder(HttpServletRequest, ServletRequestDataBinder)</code> instead
*/
@Deprecated
protected void initBinder(ServletRequest request, ServletRequestDataBinder binder) throws Exception {
}
@@ -618,13 +606,13 @@ public class MultiActionController extends AbstractController implements LastMod
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception class [" + exceptionClass.getName() + "]");
}
Method handler = (Method) this.exceptionHandlerMap.get(exceptionClass);
Method handler = this.exceptionHandlerMap.get(exceptionClass);
while (handler == null && !exceptionClass.equals(Throwable.class)) {
if (logger.isDebugEnabled()) {
logger.debug("Trying to find handler for exception superclass [" + exceptionClass.getName() + "]");
}
exceptionClass = exceptionClass.getSuperclass();
handler = (Method) this.exceptionHandlerMap.get(exceptionClass);
handler = this.exceptionHandlerMap.get(exceptionClass);
}
return handler;
}
@@ -646,7 +634,7 @@ public class MultiActionController extends AbstractController implements LastMod
logger.debug("Invoking exception handler [" + handler + "] for exception: " + ex);
}
try {
Object returnValue = handler.invoke(this.delegate, new Object[] {request, response, ex});
Object returnValue = handler.invoke(this.delegate, request, response, ex);
return massageReturnValueIfNecessary(returnValue);
}
catch (InvocationTargetException ex2) {

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.
@@ -28,8 +28,8 @@ import org.springframework.util.StringUtils;
import org.springframework.web.util.WebUtils;
/**
* Implementation of MethodNameResolver which supports several strategies for
* mapping parameter values to the names of methods to invoke.
* Implementation of {@link MethodNameResolver} which supports several strategies
* for mapping parameter values to the names of methods to invoke.
*
* <p>The simplest strategy looks for a specific named parameter, whose value is
* considered the name of the method to invoke. The name of the parameter may be
@@ -163,8 +163,7 @@ public class ParameterMethodNameResolver implements MethodNameResolver {
// Check parameter names where the very existence of each parameter
// means that a method of the same name should be invoked, if any.
if (this.methodParamNames != null) {
for (int i = 0; i < this.methodParamNames.length; ++i) {
String candidate = this.methodParamNames[i];
for (String candidate : this.methodParamNames) {
if (WebUtils.hasSubmitParameter(request, candidate)) {
methodName = candidate;
if (logger.isDebugEnabled()) {

View File

@@ -1,12 +1,12 @@
/*
* Copyright 2002-2005 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.
* You may obtain a copy of the License at
*
*
* http://www.apache.org/licenses/LICENSE-2.0
*
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@@ -16,7 +16,7 @@
package org.springframework.web.servlet.mvc.multiaction;
import java.util.Iterator;
import java.util.Enumeration;
import java.util.Properties;
import org.springframework.beans.factory.InitializingBean;
@@ -25,7 +25,7 @@ import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
/**
* The most flexible out-of-the-box implementation of the MethodNameResolver
* The most flexible out-of-the-box implementation of the {@link MethodNameResolver}
* interface. Uses <code>java.util.Properties</code> to define the mapping
* between the URL of incoming requests and the corresponding method name.
* Such properties can be held in an XML document.
@@ -85,8 +85,9 @@ public class PropertiesMethodNameResolver extends AbstractUrlMethodNameResolver
if (methodName != null) {
return methodName;
}
for (Iterator it = this.mappings.keySet().iterator(); it.hasNext();) {
String registeredPath = (String) it.next();
Enumeration propNames = this.mappings.propertyNames();
while (propNames.hasMoreElements()) {
String registeredPath = (String) propNames.nextElement();
if (this.pathMatcher.match(registeredPath, urlPath)) {
return (String) this.mappings.get(registeredPath);
}

View File

@@ -66,11 +66,11 @@ public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandl
@Override
protected String[] buildUrlsForHandler(String beanName, Class beanClass) {
List urls = new ArrayList();
List<String> urls = new ArrayList<String>();
urls.add(generatePathMapping(beanName));
String[] aliases = getApplicationContext().getAliases(beanName);
for (int i = 0; i < aliases.length; i++) {
urls.add(generatePathMapping(aliases[i]));
for (String alias : aliases) {
urls.add(generatePathMapping(alias));
}
return StringUtils.toStringArray(urls);
}
@@ -80,7 +80,7 @@ public class ControllerBeanNameHandlerMapping extends AbstractControllerUrlHandl
*/
protected String generatePathMapping(String beanName) {
String name = (beanName.startsWith("/") ? beanName : "/" + beanName);
StringBuffer path = new StringBuffer();
StringBuilder path = new StringBuilder();
if (!name.startsWith(this.urlPrefix)) {
path.append(this.urlPrefix);
}

View File

@@ -134,7 +134,7 @@ public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHand
* @return the URL path mappings for the given controller
*/
protected String[] generatePathMappings(Class beanClass) {
StringBuffer pathMapping = buildPathPrefix(beanClass);
StringBuilder pathMapping = buildPathPrefix(beanClass);
String className = ClassUtils.getShortName(beanClass);
String path = (className.endsWith(CONTROLLER_SUFFIX) ?
className.substring(0, className.indexOf(CONTROLLER_SUFFIX)) : className);
@@ -159,8 +159,8 @@ public class ControllerClassNameHandlerMapping extends AbstractControllerUrlHand
* @param beanClass the controller bean class to generate a mapping for
* @return the path prefix, potentially including subpackage names as path elements
*/
private StringBuffer buildPathPrefix(Class beanClass) {
StringBuffer pathMapping = new StringBuffer();
private StringBuilder buildPathPrefix(Class beanClass) {
StringBuilder pathMapping = new StringBuilder();
if (this.pathPrefix != null) {
pathMapping.append(this.pathPrefix);
pathMapping.append("/");

View File

@@ -325,7 +325,7 @@ public class BindStatus {
@Override
public String toString() {
StringBuffer sb = new StringBuffer("BindStatus: ");
StringBuilder sb = new StringBuilder("BindStatus: ");
sb.append("expression=[").append(this.expression).append("]; ");
sb.append("value=[").append(this.value).append("]");
if (isError()) {

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,13 +18,10 @@ package org.springframework.web.servlet.support;
import java.util.Locale;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.jstl.core.Config;
import org.springframework.util.ClassUtils;
/**
* JSP-aware (and JSTL-aware) subclass of RequestContext, allowing for
* population of the context from a <code>javax.servlet.jsp.PageContext</code>.
@@ -57,7 +54,7 @@ public class JspAwareRequestContext extends RequestContext {
* @param model the model attributes for the current view
* (can be <code>null</code>, using the request attributes for Errors retrieval)
*/
public JspAwareRequestContext(PageContext pageContext, Map model) {
public JspAwareRequestContext(PageContext pageContext, Map<String, Object> model) {
initContext(pageContext, model);
}
@@ -68,7 +65,7 @@ public class JspAwareRequestContext extends RequestContext {
* @param model the model attributes for the current view
* (can be <code>null</code>, using the request attributes for Errors retrieval)
*/
protected void initContext(PageContext pageContext, Map model) {
protected void initContext(PageContext pageContext, Map<String, Object> model) {
if (!(pageContext.getRequest() instanceof HttpServletRequest)) {
throw new IllegalArgumentException("RequestContext only supports HTTP requests");
}

View File

@@ -91,7 +91,7 @@ public class RequestContext {
private HttpServletRequest request;
private Map model;
private Map<String, Object> model;
private WebApplicationContext webApplicationContext;
@@ -103,7 +103,7 @@ public class RequestContext {
private UrlPathHelper urlPathHelper;
private Map errorsMap;
private Map<String, Errors> errorsMap;
/**
@@ -153,7 +153,7 @@ public class RequestContext {
* @see org.springframework.web.servlet.DispatcherServlet
* @see #RequestContext(javax.servlet.http.HttpServletRequest, javax.servlet.ServletContext, Map)
*/
public RequestContext(HttpServletRequest request, Map model) {
public RequestContext(HttpServletRequest request, Map<String, Object> model) {
initContext(request, null, model);
}
@@ -172,7 +172,7 @@ public class RequestContext {
* @see org.springframework.web.context.WebApplicationContext
* @see org.springframework.web.servlet.DispatcherServlet
*/
public RequestContext(HttpServletRequest request, ServletContext servletContext, Map model) {
public RequestContext(HttpServletRequest request, ServletContext servletContext, Map<String, Object> model) {
initContext(request, servletContext, model);
}
@@ -199,7 +199,7 @@ public class RequestContext {
* @see org.springframework.web.servlet.DispatcherServlet#LOCALE_RESOLVER_ATTRIBUTE
* @see org.springframework.web.servlet.DispatcherServlet#THEME_RESOLVER_ATTRIBUTE
*/
protected void initContext(HttpServletRequest request, ServletContext servletContext, Map model) {
protected void initContext(HttpServletRequest request, ServletContext servletContext, Map<String, Object> model) {
this.request = request;
this.model = model;
@@ -326,7 +326,7 @@ public class RequestContext {
* @see org.springframework.web.util.WebUtils#isDefaultHtmlEscape
*/
public void setDefaultHtmlEscape(boolean defaultHtmlEscape) {
this.defaultHtmlEscape = Boolean.valueOf(defaultHtmlEscape);
this.defaultHtmlEscape = defaultHtmlEscape;
}
/**
@@ -334,7 +334,7 @@ public class RequestContext {
* Falls back to <code>false</code> in case of no explicit default given.
*/
public boolean isDefaultHtmlEscape() {
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape.booleanValue());
return (this.defaultHtmlEscape != null && this.defaultHtmlEscape);
}
/**
@@ -640,16 +640,13 @@ public class RequestContext {
*/
public Errors getErrors(String name, boolean htmlEscape) {
if (this.errorsMap == null) {
this.errorsMap = new HashMap();
this.errorsMap = new HashMap<String, Errors>();
}
Errors errors = (Errors) this.errorsMap.get(name);
Errors errors = this.errorsMap.get(name);
boolean put = false;
if (errors == null) {
errors = (Errors) getModelObject(BindingResult.MODEL_KEY_PREFIX + name);
// Check old BindException prefix for backwards compatibility.
if (errors == null) {
errors = (Errors) getModelObject(BindException.ERROR_KEY_PREFIX + name);
}
if (errors instanceof BindException) {
errors = ((BindException) errors).getBindingResult();
}

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,8 +42,8 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu
/** Whether we should cache views, once resolved */
private boolean cache = true;
/** Map from view name to View instance */
private final Map viewCache = new HashMap();
/** Map from view key to View instance */
private final Map<Object, View> viewCache = new HashMap<Object, View>();
/**
@@ -72,7 +72,7 @@ public abstract class AbstractCachingViewResolver extends WebApplicationObjectSu
else {
Object cacheKey = getCacheKey(viewName, locale);
synchronized (this.viewCache) {
View view = (View) this.viewCache.get(cacheKey);
View view = this.viewCache.get(cacheKey);
if (view == null) {
// Ask the subclass to create the View object.
view = createView(viewName, locale);

View File

@@ -114,7 +114,7 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView {
@Override
protected final void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (this.exposeRequestAttributes) {
for (Enumeration en = request.getAttributeNames(); en.hasMoreElements();) {
@@ -191,6 +191,6 @@ public abstract class AbstractTemplateView extends AbstractUrlBasedView {
* @throws Exception if rendering failed
*/
protected abstract void renderMergedTemplateModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception;
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception;
}

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.
@@ -78,7 +78,7 @@ public abstract class AbstractUrlBasedView extends AbstractView implements Initi
@Override
public String toString() {
StringBuffer sb = new StringBuffer(super.toString());
StringBuilder sb = new StringBuilder(super.toString());
sb.append("; URL [").append(getUrl()).append("]");
return sb.toString();
}

View File

@@ -20,7 +20,6 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
@@ -69,7 +68,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
private String requestContextAttribute;
/** Map of static attributes, keyed by attribute name (String) */
private final Map staticAttributes = new HashMap();
private final Map<String, Object> staticAttributes = new HashMap<String, Object>();
/**
@@ -178,17 +177,10 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
* <p>Can be populated with a "map" or "props" element in XML bean definitions.
* @param attributes Map with name Strings as keys and attribute objects as values
*/
public void setAttributesMap(Map attributes) {
public void setAttributesMap(Map<String, ?> attributes) {
if (attributes != null) {
Iterator it = attributes.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
if (!(key instanceof String)) {
throw new IllegalArgumentException(
"Invalid attribute key [" + key + "]: only Strings allowed");
}
addStaticAttribute((String) key, entry.getValue());
for (Map.Entry<String, ?> entry : attributes.entrySet()) {
addStaticAttribute(entry.getKey(), entry.getValue());
}
}
}
@@ -200,7 +192,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
* "attributesMap[myKey]". This is particularly useful for
* adding or overriding entries in child view definitions.
*/
public Map getAttributesMap() {
public Map<String, Object> getAttributesMap() {
return this.staticAttributes;
}
@@ -235,14 +227,15 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
* Delegates to renderMergedOutputModel for the actual rendering.
* @see #renderMergedOutputModel
*/
public void render(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (logger.isTraceEnabled()) {
logger.trace("Rendering view with name '" + this.beanName + "' with model " + model +
" and static attributes " + this.staticAttributes);
}
// Consolidate static and dynamic model attributes.
Map mergedModel = new HashMap(this.staticAttributes.size() + (model != null ? model.size() : 0));
Map<String, Object> mergedModel =
new HashMap<String, Object>(this.staticAttributes.size() + (model != null ? model.size() : 0));
mergedModel.putAll(this.staticAttributes);
if (model != null) {
mergedModel.putAll(model);
@@ -268,7 +261,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
* @see #setRequestContextAttribute
* @see org.springframework.web.servlet.support.RequestContext
*/
protected RequestContext createRequestContext(HttpServletRequest request, Map model) {
protected RequestContext createRequestContext(HttpServletRequest request, Map<String, Object> model) {
return new RequestContext(request, getServletContext(), model);
}
@@ -313,7 +306,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
* @throws Exception if rendering failed
*/
protected abstract void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception;
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception;
/**
@@ -323,15 +316,9 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
* @param model Map of model objects to expose
* @param request current HTTP request
*/
protected void exposeModelAsRequestAttributes(Map model, HttpServletRequest request) throws Exception {
Iterator it = model.entrySet().iterator();
while (it.hasNext()) {
Map.Entry entry = (Map.Entry) it.next();
if (!(entry.getKey() instanceof String)) {
throw new IllegalArgumentException(
"Invalid key [" + entry.getKey() + "] in model Map: only Strings allowed as model keys");
}
String modelName = (String) entry.getKey();
protected void exposeModelAsRequestAttributes(Map<String, Object> model, HttpServletRequest request) throws Exception {
for (Map.Entry<String, Object> entry : model.entrySet()) {
String modelName = entry.getKey();
Object modelValue = entry.getValue();
if (modelValue != null) {
request.setAttribute(modelName, modelValue);
@@ -379,7 +366,7 @@ public abstract class AbstractView extends WebApplicationObjectSupport implement
@Override
public String toString() {
StringBuffer sb = new StringBuffer(getClass().getName());
StringBuilder sb = new StringBuilder(getClass().getName());
if (getBeanName() != null) {
sb.append(": name '").append(getBeanName()).append("'");
}

View File

@@ -128,7 +128,7 @@ public class InternalResourceView extends AbstractUrlBasedView {
* feature exists for Servlet 2.3 containers and misbehaving 2.4 containers.
*/
public void setExposeForwardAttributes(boolean exposeForwardAttributes) {
this.exposeForwardAttributes = Boolean.valueOf(exposeForwardAttributes);
this.exposeForwardAttributes = exposeForwardAttributes;
}
/**
@@ -200,7 +200,7 @@ public class InternalResourceView extends AbstractUrlBasedView {
*/
@Override
protected void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Determine which request handle to expose to the RequestDispatcher.
HttpServletRequest requestToExpose = getRequestToExpose(request);
@@ -331,7 +331,7 @@ public class InternalResourceView extends AbstractUrlBasedView {
* @see org.springframework.web.util.WebUtils#exposeForwardRequestAttributes
*/
protected void exposeForwardRequestAttributes(HttpServletRequest request) {
if (this.exposeForwardAttributes != null && this.exposeForwardAttributes.booleanValue()) {
if (this.exposeForwardAttributes != null && this.exposeForwardAttributes) {
WebUtils.exposeForwardRequestAttributes(request);
}
}

View File

@@ -26,7 +26,6 @@ import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -191,10 +190,11 @@ public class RedirectView extends AbstractUrlBasedView {
*/
@Override
protected void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws IOException {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws IOException {
// Prepare target URL.
StringBuffer targetUrl = new StringBuffer();
StringBuilder targetUrl = new StringBuilder();
if (this.contextRelative && getUrl().startsWith("/")) {
// Do not apply context path to relative URLs.
targetUrl.append(request.getContextPath());
@@ -217,13 +217,13 @@ public class RedirectView extends AbstractUrlBasedView {
/**
* Append query properties to the redirect URL.
* Stringifies, URL-encodes and formats model attributes as query properties.
* @param targetUrl the StringBuffer to append the properties to
* @param targetUrl the StringBuilder to append the properties to
* @param model Map that contains model attributes
* @param encodingScheme the encoding scheme to use
* @throws UnsupportedEncodingException if string encoding failed
* @see #queryProperties
*/
protected void appendQueryProperties(StringBuffer targetUrl, Map model, String encodingScheme)
protected void appendQueryProperties(StringBuilder targetUrl, Map<String, Object> model, String encodingScheme)
throws UnsupportedEncodingException {
// Extract anchor fragment, if any.
@@ -236,10 +236,7 @@ public class RedirectView extends AbstractUrlBasedView {
// If there aren't already some parameters, we need a "?".
boolean first = (getUrl().indexOf('?') < 0);
Iterator entries = queryProperties(model).entrySet().iterator();
while (entries.hasNext()) {
Map.Entry entry = (Map.Entry) entries.next();
String key = entry.getKey().toString();
for (Map.Entry<String, Object> entry : queryProperties(model).entrySet()) {
Object rawValue = entry.getValue();
Iterator valueIter = null;
if (rawValue != null && rawValue.getClass().isArray()) {
@@ -260,7 +257,7 @@ public class RedirectView extends AbstractUrlBasedView {
else {
targetUrl.append('&');
}
String encodedKey = urlEncode(key, encodingScheme);
String encodedKey = urlEncode(entry.getKey(), encodingScheme);
String encodedValue = (value != null ? urlEncode(value.toString(), encodingScheme) : "");
targetUrl.append(encodedKey).append('=').append(encodedValue);
}
@@ -282,14 +279,11 @@ public class RedirectView extends AbstractUrlBasedView {
* @return the filtered Map of eligible query properties
* @see #isEligibleProperty(String, Object)
*/
protected Map queryProperties(Map model) {
Map result = new LinkedHashMap();
for (Iterator it = model.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String key = entry.getKey().toString();
Object value = entry.getValue();
if (isEligibleProperty(key, value)) {
result.put(key, value);
protected Map<String, Object> queryProperties(Map<String, Object> model) {
Map<String, Object> result = new LinkedHashMap<String, Object>();
for (Map.Entry<String, Object> entry : model.entrySet()) {
if (isEligibleProperty(entry.getKey(), entry.getValue())) {
result.put(entry.getKey(), entry.getValue());
}
}
return result;
@@ -332,8 +326,7 @@ public class RedirectView extends AbstractUrlBasedView {
if (coll.isEmpty()) {
return false;
}
for (Iterator it = coll.iterator(); it.hasNext();) {
Object element = it.next();
for (Object element : coll) {
if (!isEligibleValue(element)) {
return false;
}

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.
@@ -78,10 +78,12 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl
private Locale[] localesToInitialize;
/* Locale -> BeanFactory */
private final Map localeCache = new HashMap();
private final Map<Locale, BeanFactory> localeCache =
new HashMap<Locale, BeanFactory>();
/* List of ResourceBundle -> BeanFactory */
private final Map bundleCache = new HashMap();
private final Map<List<ResourceBundle>, ConfigurableApplicationContext> bundleCache =
new HashMap<List<ResourceBundle>, ConfigurableApplicationContext>();
public void setOrder(int order) {
@@ -177,8 +179,8 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl
@Override
protected void initApplicationContext() throws BeansException {
if (this.localesToInitialize != null) {
for (int i = 0; i < this.localesToInitialize.length; i++) {
initFactory(this.localesToInitialize[i]);
for (Locale locale : this.localesToInitialize) {
initFactory(locale);
}
}
}
@@ -187,7 +189,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl
protected View loadView(String viewName, Locale locale) throws Exception {
BeanFactory factory = initFactory(locale);
try {
return (View) factory.getBean(viewName, View.class);
return factory.getBean(viewName, View.class);
}
catch (NoSuchBeanDefinitionException ex) {
// to allow for ViewResolver chaining
@@ -207,23 +209,23 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl
// Try to find cached factory for Locale:
// Have we already encountered that Locale before?
if (isCache()) {
BeanFactory cachedFactory = (BeanFactory) this.localeCache.get(locale);
BeanFactory cachedFactory = this.localeCache.get(locale);
if (cachedFactory != null) {
return cachedFactory;
}
}
// Build list of ResourceBundle references for Locale.
List bundles = new LinkedList();
for (int i = 0; i < this.basenames.length; i++) {
ResourceBundle bundle = getBundle(this.basenames[i], locale);
List<ResourceBundle> bundles = new LinkedList<ResourceBundle>();
for (String basename : this.basenames) {
ResourceBundle bundle = getBundle(basename, locale);
bundles.add(bundle);
}
// Try to find cached factory for ResourceBundle list:
// even if Locale was different, same bundles might have been found.
if (isCache()) {
BeanFactory cachedFactory = (BeanFactory) this.bundleCache.get(bundles);
BeanFactory cachedFactory = this.bundleCache.get(bundles);
if (cachedFactory != null) {
this.localeCache.put(locale, cachedFactory);
return cachedFactory;
@@ -238,8 +240,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl
// Load bean definitions from resource bundle.
PropertiesBeanDefinitionReader reader = new PropertiesBeanDefinitionReader(factory);
reader.setDefaultParentBean(this.defaultParentView);
for (int i = 0; i < bundles.size(); i++) {
ResourceBundle bundle = (ResourceBundle) bundles.get(i);
for (ResourceBundle bundle : bundles) {
reader.registerBeanDefinitions(bundle);
}
@@ -271,8 +272,7 @@ public class ResourceBundleViewResolver extends AbstractCachingViewResolver impl
* Close the bundle View factories on context shutdown.
*/
public void destroy() throws BeansException {
for (Iterator it = this.bundleCache.values().iterator(); it.hasNext();) {
ConfigurableApplicationContext factory = (ConfigurableApplicationContext) it.next();
for (ConfigurableApplicationContext factory : this.bundleCache.values()) {
factory.close();
}
this.localeCache.clear();

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.
@@ -23,6 +23,7 @@ import java.util.Properties;
import org.springframework.beans.BeanUtils;
import org.springframework.core.Ordered;
import org.springframework.util.CollectionUtils;
import org.springframework.util.PatternMatchUtils;
import org.springframework.web.servlet.View;
@@ -115,7 +116,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements
private int order = Integer.MAX_VALUE;
/** Map of static attributes, keyed by attribute name (String) */
private final Map staticAttributes = new HashMap();
private final Map<String, Object> staticAttributes = new HashMap<String, Object>();
/**
@@ -271,7 +272,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements
* @see AbstractView#setAttributes
*/
public void setAttributes(Properties props) {
setAttributesMap(props);
CollectionUtils.mergePropertiesIntoMap(props, this.staticAttributes);
}
/**
@@ -281,7 +282,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements
* @param attributes Map with name Strings as keys and attribute objects as values
* @see AbstractView#setAttributesMap
*/
public void setAttributesMap(Map attributes) {
public void setAttributesMap(Map<String, ?> attributes) {
if (attributes != null) {
this.staticAttributes.putAll(attributes);
}
@@ -294,7 +295,7 @@ public class UrlBasedViewResolver extends AbstractCachingViewResolver implements
* "attributesMap[myKey]". This is particularly useful for
* adding or overriding entries in child view definitions.
*/
public Map getAttributesMap() {
public Map<String, Object> getAttributesMap() {
return this.staticAttributes;
}

View File

@@ -18,12 +18,12 @@ package org.springframework.web.servlet.view.document;
import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
@@ -55,9 +55,9 @@ import org.springframework.web.servlet.view.AbstractView;
*
* <p>As an example, you can try this snippet:
*
* <pre>
* <pre class="code">
* protected void buildExcelDocument(
* Map model, HSSFWorkbook workbook,
* Map&lt;String, Object&gt; model, HSSFWorkbook workbook,
* HttpServletRequest request, HttpServletResponse response) {
*
* // Go to the first sheet.
@@ -131,7 +131,7 @@ public abstract class AbstractExcelView extends AbstractView {
*/
@Override
protected final void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
HSSFWorkbook workbook;
if (this.url != null) {
@@ -185,7 +185,7 @@ public abstract class AbstractExcelView extends AbstractView {
* @param response in case we need to set cookies. Shouldn't write to it.
*/
protected abstract void buildExcelDocument(
Map model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
Map<String, Object> model, HSSFWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
throws Exception;
@@ -217,7 +217,7 @@ public abstract class AbstractExcelView extends AbstractView {
*/
protected void setText(HSSFCell cell, String text) {
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(text);
cell.setCellValue(new HSSFRichTextString(text));
}
}

View File

@@ -56,16 +56,18 @@ import org.springframework.web.servlet.view.AbstractView;
*
* <p>As an example, you can try this snippet:
*
* <pre>
* protected void buildExcelDocument(Map model, WritableWorkbook workbook, HttpServletRequest request,
* HttpServletResponse response) {
* if (workbook.getNumberOfSheets() == 0) {
* workbook.createSheet(&quot;Spring&quot;, 0);
* }
* <pre class="code">
* protected void buildExcelDocument(
* Map&lt;String, Object&gt; model, WritableWorkbook workbook,
* HttpServletRequest request, HttpServletResponse response) {
*
* if (workbook.getNumberOfSheets() == 0) {
* workbook.createSheet(&quot;Spring&quot;, 0);
* }
*
* WritableSheet sheet = workbook.getSheet(&quot;Spring&quot;);
* Label label = new Label(0, 0, &quot;This is a nice label&quot;);
* sheet.addCell(label);
* WritableSheet sheet = workbook.getSheet(&quot;Spring&quot;);
* Label label = new Label(0, 0, &quot;This is a nice label&quot;);
* sheet.addCell(label);
* }</pre>
*
* The use of this view is close to the AbstractExcelView class,
@@ -117,7 +119,7 @@ public abstract class AbstractJExcelView extends AbstractView {
*/
@Override
protected final void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Set the content type and get the output stream.
response.setContentType(getContentType());
@@ -171,8 +173,7 @@ public abstract class AbstractJExcelView extends AbstractView {
* @param response in case we need to set cookies. Shouldn't write to it.
* @throws Exception in case of failure
*/
protected abstract void buildExcelDocument(
Map model, WritableWorkbook workbook, HttpServletRequest request, HttpServletResponse response)
throws Exception;
protected abstract void buildExcelDocument(Map<String, Object> model, WritableWorkbook workbook,
HttpServletRequest request, HttpServletResponse response) throws Exception;
}

View File

@@ -41,9 +41,9 @@ import org.springframework.web.servlet.view.AbstractUrlBasedView;
*/
public abstract class AbstractPdfStamperView extends AbstractUrlBasedView {
public AbstractPdfStamperView(){
setContentType("application/pdf");
}
public AbstractPdfStamperView(){
setContentType("application/pdf");
}
@Override
@@ -51,21 +51,21 @@ public abstract class AbstractPdfStamperView extends AbstractUrlBasedView {
return true;
}
@Override
protected final void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception{
@Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// IE workaround: write into byte array first.
ByteArrayOutputStream baos = createTemporaryOutputStream();
PdfReader reader = readPdfResource();
PdfStamper stamper = new PdfStamper(reader, baos);
mergePdfDocument(model, stamper, request, response);
stamper.close();
PdfReader reader = readPdfResource();
PdfStamper stamper = new PdfStamper(reader, baos);
mergePdfDocument(model, stamper, request, response);
stamper.close();
// Flush to HTTP response.
writeToResponse(response, baos);
}
}
/**
* Read the raw PDF resource into an iText PdfReader.
@@ -79,34 +79,33 @@ public abstract class AbstractPdfStamperView extends AbstractUrlBasedView {
return new PdfReader(getApplicationContext().getResource(getUrl()).getInputStream());
}
/**
/**
* Subclasses must implement this method to merge the PDF form
* with the given model data.
* <p>This is where you are able to set values on the AcroForm.
* An example of what can be done at this level is:
* <p>This is where you are able to set values on the AcroForm.
* An example of what can be done at this level is:
* <pre class="code">
* // get the form from the document
* AcroFields form = stamper.getAcroFields();
*
* // set some values on the form
* form.setField("field1", "value1");
* form.setField("field2", "Vvlue2");
* // get the form from the document
* AcroFields form = stamper.getAcroFields();
*
* // set the disposition and filename
* response.setHeader("Content-disposition", "attachment; FILENAME=someName.pdf");</pre>
* // set some values on the form
* form.setField("field1", "value1");
* form.setField("field2", "Vvlue2");
*
* // set the disposition and filename
* response.setHeader("Content-disposition", "attachment; FILENAME=someName.pdf");</pre>
* <p>Note that the passed-in HTTP response is just supposed to be used
* for setting cookies or other HTTP headers. The built PDF document itself
* will automatically get written to the response after this method returns.
* @param model the model Map
* @param stamper the PdfStamper instance that will contain the AcroFields.
* @param stamper the PdfStamper instance that will contain the AcroFields.
* You may also customize this PdfStamper instance according to your needs,
* e.g. setting the "formFlattening" property.
* @param request in case we need locale etc. Shouldn't look at attributes.
* @param response in case we need to set cookies. Shouldn't write to it.
* @throws Exception any exception that occured during document building
*/
protected abstract void mergePdfDocument(
Map model, PdfStamper stamper, HttpServletRequest request, HttpServletResponse response)
throws Exception;
*/
protected abstract void mergePdfDocument(Map<String, Object> model, PdfStamper stamper,
HttpServletRequest request, HttpServletResponse response) throws Exception;
}

View File

@@ -19,7 +19,6 @@ package org.springframework.web.servlet.view.document;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@@ -63,7 +62,7 @@ public abstract class AbstractPdfView extends AbstractView {
@Override
protected final void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// IE workaround: write into byte array first.
ByteArrayOutputStream baos = createTemporaryOutputStream();
@@ -120,7 +119,7 @@ public abstract class AbstractPdfView extends AbstractView {
* @see com.lowagie.text.pdf.PdfWriter#setViewerPreferences
* @see #getViewerPreferences()
*/
protected void prepareWriter(Map model, PdfWriter writer, HttpServletRequest request)
protected void prepareWriter(Map<String, Object> model, PdfWriter writer, HttpServletRequest request)
throws DocumentException {
writer.setViewerPreferences(getViewerPreferences());
@@ -137,7 +136,7 @@ public abstract class AbstractPdfView extends AbstractView {
* @see com.lowagie.text.pdf.PdfWriter#PageLayoutSinglePage
*/
protected int getViewerPreferences() {
return PdfWriter.AllowPrinting | PdfWriter.PageLayoutSinglePage;
return PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage;
}
/**
@@ -158,7 +157,7 @@ public abstract class AbstractPdfView extends AbstractView {
* @see com.lowagie.text.Document#addCreationDate
* @see com.lowagie.text.Document#addHeader
*/
protected void buildPdfMetadata(Map model, Document document, HttpServletRequest request) {
protected void buildPdfMetadata(Map<String, Object> model, Document document, HttpServletRequest request) {
}
/**
@@ -177,9 +176,7 @@ public abstract class AbstractPdfView extends AbstractView {
* @see com.lowagie.text.Document#open()
* @see com.lowagie.text.Document#close()
*/
protected abstract void buildPdfDocument(
Map model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response)
throws Exception;
protected abstract void buildPdfDocument(Map<String, Object> model, Document document, PdfWriter writer,
HttpServletRequest request, HttpServletResponse response) throws Exception;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2008 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,19 @@ import com.sun.syndication.feed.atom.Entry;
import com.sun.syndication.feed.atom.Feed;
/**
* Abstract superclass for Atom Feed views, using java.net's <a href="https://rome.dev.java.net/">ROME</a> package.
* Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a
* template.
* Abstract superclass for Atom Feed views, using java.net's
* <a href="https://rome.dev.java.net/">ROME</a> package.
*
* <p/>Main entry points are the {@link #buildFeedMetadata(Map, WireFeed, HttpServletRequest)} and
* <p>Application-specific view classes will extend this class.
* The view will be held in the subclass itself, not in a template.
*
* <p>Main entry points are the {@link #buildFeedMetadata(Map, WireFeed, HttpServletRequest)} and
* {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)}.
*
* @author Jettro Coenradie
* @author Sergio Bossa
* <p>Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype!
*
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see #buildFeedMetadata(Map, WireFeed, HttpServletRequest)
* @see #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)
@@ -46,16 +49,14 @@ public abstract class AbstractAtomFeedView extends AbstractFeedView<Feed> {
private String feedType = DEFAULT_FEED_TYPE;
/** Sets the appropriate content type: "application/atom+xml". */
public AbstractAtomFeedView() {
setContentType("application/atom+xml");
}
/**
* Sets the Rome feed type to use.
* <p/>
* Defaults to Atom 1.0.
*
* <p>Defaults to Atom 1.0.
* @see Feed#setFeedType(String)
* @see #DEFAULT_FEED_TYPE
*/
@@ -64,42 +65,41 @@ public abstract class AbstractAtomFeedView extends AbstractFeedView<Feed> {
}
/**
* Create a new feed to hold the entries.
* <p/>
* By default returns an Atom 1.0 feed, but the subclass can specify any Feed.
*
* @return the newly created Feed instance
* Create a new Feed instance to hold the entries.
* <p>By default returns an Atom 1.0 feed, but the subclass can specify any Feed.
* @see #setFeedType(String)
* @see com.sun.syndication.feed.atom.Feed#Feed(String)
*/
@Override
protected Feed newFeed() {
return new Feed(feedType);
return new Feed(this.feedType);
}
/** Invokes {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)} to get a list of feed entries. */
/**
* Invokes {@link #buildFeedEntries(Map, HttpServletRequest, HttpServletResponse)}
* to get a list of feed entries.
*/
@Override
protected final void buildFeedEntries(Map model,
Feed feed,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
protected final void buildFeedEntries(Map<String, Object> model, Feed feed,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Entry> entries = buildFeedEntries(model, request, response);
feed.setEntries(entries);
}
/**
* Subclasses must implement this method to build feed entries, given the model.
* <p/>
* Note that the passed-in HTTP response is just supposed to be used for setting cookies or other HTTP headers. The
* built feed itself will automatically get written to the response after this method returns.
*
* <p>Note that the passed-in HTTP response is just supposed to be used for
* setting cookies or other HTTP headers. The built feed itself will automatically
* get written to the response after this method returns.
* @param model the model Map
* @param request in case we need locale etc. Shouldn't look at attributes.
* @param request in case we need locale etc. Shouldn't look at attributes.
* @param response in case we need to set cookies. Shouldn't write to it.
* @return the feed entries to be added to the feed
* @throws Exception any exception that occured during document building
* @see Entry
*/
protected abstract List<Entry> buildFeedEntries(Map model, HttpServletRequest request, HttpServletResponse response)
protected abstract List<Entry> buildFeedEntries(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2008 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.
@@ -29,22 +29,27 @@ import org.springframework.util.StringUtils;
import org.springframework.web.servlet.view.AbstractView;
/**
* Abstract base class for Atom and RSS Feed views, using java.net's <a href="https://rome.dev.java.net/">ROME</a>
* package. TypApplication-specific view classes will typically extends either {@link AbstractRssFeedView} or {@link
* AbstractAtomFeedView}, not this class.
* Abstract base class for Atom and RSS Feed views, using java.net's
* <a href="https://rome.dev.java.net/">ROME</a> package.
*
* <p>Application-specific view classes will typically extend from either
* {@link AbstractRssFeedView} or {@link AbstractAtomFeedView} instead of from this class.
*
* <p>Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype!
*
* @author Jettro Coenradie
* @author Sergio Bossa
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see AbstractRssFeedView
* @see AbstractAtomFeedView
* @since 3.0
*/
public abstract class AbstractFeedView<T extends WireFeed> extends AbstractView {
@Override
protected final void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
T wireFeed = newFeed();
buildFeedMetadata(model, wireFeed, request);
buildFeedEntries(model, wireFeed, request, response);
@@ -62,40 +67,33 @@ public abstract class AbstractFeedView<T extends WireFeed> extends AbstractView
/**
* Create a new feed to hold the entries.
*
* @return the newly created Feed instance
*/
protected abstract T newFeed();
/**
* Populate the feed metadata (title, link, description, etc.).
* <p/>
* Default is an empty implementation. Subclasses can override this method to add meta fields such as title, link
* description, etc.
*
* @param model the model, in case meta information must be populated from it
* @param feed the feed being populated
* <p>Default is an empty implementation. Subclasses can override this method
* to add meta fields such as title, link description, etc.
* @param model the model, in case meta information must be populated from it
* @param feed the feed being populated
* @param request in case we need locale etc. Shouldn't look at attributes.
*/
protected void buildFeedMetadata(Map model, T feed, HttpServletRequest request) {
protected void buildFeedMetadata(Map<String, Object> model, T feed, HttpServletRequest request) {
}
/**
* Subclasses must implement this method to build feed entries, given the model.
* <p/>
* Note that the passed-in HTTP response is just supposed to be used for setting cookies or other HTTP headers. The
* built feed itself will automatically get written to the response after this method returns.
*
* @param model the model Map
* @param feed the feed to add entries to
* @param request in case we need locale etc. Shouldn't look at attributes.
* <p>Note that the passed-in HTTP response is just supposed to be used for
* setting cookies or other HTTP headers. The built feed itself will automatically
* get written to the response after this method returns.
* @param model the model Map
* @param feed the feed to add entries to
* @param request in case we need locale etc. Shouldn't look at attributes.
* @param response in case we need to set cookies. Shouldn't write to it.
* @throws Exception any exception that occured during building
*/
protected abstract void buildFeedEntries(Map model,
T feed,
HttpServletRequest request,
HttpServletResponse response) throws Exception;
protected abstract void buildFeedEntries(Map<String, Object> model, T feed,
HttpServletRequest request, HttpServletResponse response) throws Exception;
}

View File

@@ -26,56 +26,55 @@ import com.sun.syndication.feed.rss.Channel;
import com.sun.syndication.feed.rss.Item;
/**
* Abstract superclass for RSS Feed views, using java.net's <a href="https://rome.dev.java.net/">ROME</a> package.
* Application-specific view classes will extend this class. The view will be held in the subclass itself, not in a
* template.
* Abstract superclass for RSS Feed views, using java.net's
* <a href="https://rome.dev.java.net/">ROME</a> package.
*
* <p/>Main entry points are the {@link #buildFeedMetadata(Map, WireFeed , HttpServletRequest)} and {@link
* #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)}.
* <p>Application-specific view classes will extend this class.
* The view will be held in the subclass itself, not in a template.
*
* <p/>Main entry points are the {@link #buildFeedMetadata(Map, WireFeed , HttpServletRequest)}
* and {@link #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)}.
*
* <p>Thanks to Jettro Coenradie and Sergio Bossa for the original feed view prototype!
*
* @author Jettro Coenradie
* @author Sergio Bossa
* @author Arjen Poutsma
* @author Juergen Hoeller
* @since 3.0
* @see #buildFeedMetadata(Map, WireFeed , HttpServletRequest)
* @see #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)
* @since 3.0
*/
public abstract class AbstractRssFeedView extends AbstractFeedView<Channel> {
/** Sets the appropriate content type: "application/rss+xml". */
protected AbstractRssFeedView() {
public AbstractRssFeedView() {
setContentType("application/rss+xml");
}
/**
* Create a new channel to hold the entries.
*
* <p/>By default returns an RSS 2.0 channel, but the subclass can specify any channel.
*
* @return the newly created Feed instance
* @see Channel#Channel(String)
* Create a new Channel instance to hold the entries.
* <p>By default returns an RSS 2.0 channel, but the subclass can specify any channel.
*/
@Override
protected Channel newFeed() {
return new Channel("rss_2.0");
}
/** Invokes {@link #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)} to get a list of feed items. */
/**
* Invokes {@link #buildFeedItems(Map, HttpServletRequest, HttpServletResponse)}
* to get a list of feed items.
*/
@Override
protected final void buildFeedEntries(Map model,
Channel channel,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
protected final void buildFeedEntries(Map<String, Object> model, Channel channel,
HttpServletRequest request, HttpServletResponse response) throws Exception {
List<Item> items = buildFeedItems(model, request, response);
channel.setItems(items);
}
/**
* Subclasses must implement this method to build feed items, given the model.
*
* <p/>Note that the passed-in HTTP response is just supposed to be used for setting cookies or other HTTP headers. The
* built feed itself will automatically get written to the response after this method returns.
*
* <p>Note that the passed-in HTTP response is just supposed to be used for
* setting cookies or other HTTP headers. The built feed itself will automatically
* get written to the response after this method returns.
* @param model the model Map
* @param request in case we need locale etc. Shouldn't look at attributes.
* @param response in case we need to set cookies. Shouldn't write to it.
@@ -83,6 +82,8 @@ public abstract class AbstractRssFeedView extends AbstractFeedView<Channel> {
* @throws Exception any exception that occured during document building
* @see Item
*/
protected abstract List<Item> buildFeedItems(Map model, HttpServletRequest request, HttpServletResponse response)
protected abstract List<Item> buildFeedItems(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}

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,9 @@ package org.springframework.web.servlet.view.freemarker;
import java.io.IOException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
import javax.servlet.GenericServlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
@@ -171,7 +171,7 @@ public class FreeMarkerView extends AbstractTemplateView {
*/
protected FreeMarkerConfig autodetectConfiguration() throws BeansException {
try {
return (FreeMarkerConfig) BeanFactoryUtils.beanOfTypeIncludingAncestors(
return BeanFactoryUtils.beanOfTypeIncludingAncestors(
getApplicationContext(), FreeMarkerConfig.class, true, false);
}
catch (NoSuchBeanDefinitionException ex) {
@@ -221,7 +221,7 @@ public class FreeMarkerView extends AbstractTemplateView {
*/
@Override
protected void renderMergedTemplateModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
exposeHelpers(model, request);
doRender(model, request, response);
@@ -237,7 +237,7 @@ public class FreeMarkerView extends AbstractTemplateView {
* @throws Exception if there's a fatal error while we're adding information to the context
* @see #renderMergedTemplateModel
*/
protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
}
/**
@@ -263,7 +263,7 @@ public class FreeMarkerView extends AbstractTemplateView {
* @see #processTemplate
* @see freemarker.ext.servlet.FreemarkerServlet
*/
protected void doRender(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
protected void doRender(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Expose model to JSP tags (as request attributes).
exposeModelAsRequestAttributes(model, request);
@@ -340,7 +340,7 @@ public class FreeMarkerView extends AbstractTemplateView {
* @throws TemplateException if thrown by FreeMarker
* @see freemarker.template.Template#process(Object, java.io.Writer)
*/
protected void processTemplate(Template template, Map model, HttpServletResponse response)
protected void processTemplate(Template template, Map<String, Object> model, HttpServletResponse response)
throws IOException, TemplateException {
template.process(model, response.getWriter());
@@ -378,8 +378,8 @@ public class FreeMarkerView extends AbstractTemplateView {
return null;
}
public Enumeration getInitParameterNames() {
return Collections.enumeration(Collections.EMPTY_SET);
public Enumeration<String> getInitParameterNames() {
return Collections.enumeration(new HashSet<String>());
}
}

View File

@@ -17,10 +17,7 @@
package org.springframework.web.servlet.view.jasperreports;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JRExporter;
@@ -57,13 +54,12 @@ public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasp
* for a pre-defined output format.
*/
@Override
protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response)
protected void renderReport(JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response)
throws Exception {
JRExporter exporter = createExporter();
// Set exporter parameters - overriding with values from the Model.
Map mergedExporterParameters = mergeExporterParameters(model);
Map mergedExporterParameters = getConvertedExporterParameters();
if (!CollectionUtils.isEmpty(mergedExporterParameters)) {
exporter.setParameters(mergedExporterParameters);
}
@@ -76,28 +72,6 @@ public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasp
}
}
/**
* Merges the configured JRExporterParameters with any specified in the supplied model data.
* JRExporterParameters in the model override those specified in the configuration.
* @see #setExporterParameters(java.util.Map)
*/
protected Map mergeExporterParameters(Map model) {
Map mergedParameters = new HashMap();
Map convertedExporterParameters = getConvertedExporterParameters();
if (!CollectionUtils.isEmpty(convertedExporterParameters)) {
mergedParameters.putAll(convertedExporterParameters);
}
for (Iterator it = model.keySet().iterator(); it.hasNext();) {
Object key = it.next();
if (key instanceof JRExporterParameter) {
Object value = model.get(key);
Object convertedValue = convertParameterValue((JRExporterParameter) key, value);
mergedParameters.put(key, convertedValue);
}
}
return mergedParameters;
}
/**
* We need to write text to the response Writer.
* @param exporter the JasperReports exporter to use
@@ -113,7 +87,7 @@ public abstract class AbstractJasperReportsSingleFormatView extends AbstractJasp
String encoding = (String) exporter.getParameter(JRExporterParameter.CHARACTER_ENCODING);
if (encoding != null) {
// Only apply encoding if content type is specified but does not contain charset clause already.
if (contentType != null && contentType.toLowerCase().indexOf(WebUtils.CONTENT_TYPE_CHARSET_PREFIX) == -1) {
if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
}
}

View File

@@ -23,7 +23,6 @@ import java.sql.SQLException;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
@@ -35,11 +34,10 @@ import net.sf.jasperreports.engine.JRDataSourceProvider;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.design.JRCompiler;
import net.sf.jasperreports.engine.design.JRDefaultCompiler;
import net.sf.jasperreports.engine.design.JasperDesign;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.engine.xml.JRXmlLoader;
@@ -151,23 +149,18 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* Stores the exporter parameters passed in by the user as passed in by the user. May be keyed as
* <code>String</code>s with the fully qualified name of the exporter parameter field.
*/
private Map exporterParameters = new HashMap();
private Map<?, ?> exporterParameters = new HashMap<Object, Object>();
/**
* Stores the converted exporter parameters - keyed by <code>JRExporterParameter</code>.
*/
private Map convertedExporterParameters;
private Map<JRExporterParameter, Object> convertedExporterParameters;
/**
* Stores the <code>DataSource</code>, if any, used as the report data source.
*/
private DataSource jdbcDataSource;
/**
* Holds the JRCompiler implementation to use for compiling reports on-the-fly.
*/
private JRCompiler reportCompiler = JRDefaultCompiler.getInstance();
/**
* The <code>JasperReport</code> that is used to render the view.
*/
@@ -176,7 +169,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
/**
* Holds mappings between sub-report keys and <code>JasperReport</code> objects.
*/
private Map subReports;
private Map<String, JasperReport> subReports;
/**
@@ -251,26 +244,21 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* (e.g. "net.sf.jasperreports.engine.export.JRHtmlExporterParameter.IMAGES_URI")
* and the value you wish to assign to the parameter as value
*/
public void setExporterParameters(Map parameters) {
// NOTE: Removed conversion from here since configuration of parameters
// can also happen through access to the underlying Map using
// getExporterParameters(). Conversion now happens in initApplicationContext,
// and subclasses use getConvertedExporterParameters() to access the converted
// parameter Map - robh.
public void setExporterParameters(Map<?, ?> parameters) {
this.exporterParameters = parameters;
}
/**
* Return the exporter parameters that this view uses, if any.
*/
public Map getExporterParameters() {
public Map<?, ?> getExporterParameters() {
return this.exporterParameters;
}
/**
* Allows subclasses to retrieve the converted exporter parameters.
*/
protected Map getConvertedExporterParameters() {
protected Map<JRExporterParameter, Object> getConvertedExporterParameters() {
return this.convertedExporterParameters;
}
@@ -289,24 +277,6 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
return this.jdbcDataSource;
}
/**
* Specify the JRCompiler implementation to use for compiling a ".jrxml"
* report file on-the-fly into a report class.
* <p>By default, a JRDefaultCompiler will be used, delegating to the
* Eclipse JDT compiler or the Sun JDK compiler underneath.
* @see net.sf.jasperreports.engine.design.JRDefaultCompiler
*/
public void setReportCompiler(JRCompiler reportCompiler) {
this.reportCompiler = (reportCompiler != null ? reportCompiler : JRDefaultCompiler.getInstance());
}
/**
* Return the JRCompiler instance to use for compiling ".jrxml" report files.
*/
protected JRCompiler getReportCompiler() {
return this.reportCompiler;
}
/**
* JasperReports views do not strictly required a 'url' value.
@@ -333,7 +303,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
throw new ApplicationContextException(
"'reportDataKey' for main report is required when specifying a value for 'subReportDataKeys'");
}
this.subReports = new HashMap(this.subReportUrls.size());
this.subReports = new HashMap<String, JasperReport>(this.subReportUrls.size());
for (Enumeration urls = this.subReportUrls.propertyNames(); urls.hasMoreElements();) {
String key = (String) urls.nextElement();
String path = this.subReportUrls.getProperty(key);
@@ -373,9 +343,8 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
*/
protected final void convertExporterParameters() {
if (!CollectionUtils.isEmpty(this.exporterParameters)) {
this.convertedExporterParameters = new HashMap(this.exporterParameters.size());
for (Iterator it = this.exporterParameters.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
this.convertedExporterParameters = new HashMap<JRExporterParameter, Object>(this.exporterParameters.size());
for (Map.Entry<?, ?> entry : this.exporterParameters.entrySet()) {
JRExporterParameter exporterParameter = getExporterParameter(entry.getKey());
this.convertedExporterParameters.put(
exporterParameter, convertParameterValue(exporterParameter, entry.getValue()));
@@ -522,7 +491,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
logger.info("Compiling Jasper Report loaded from " + resource);
}
JasperDesign design = JRXmlLoader.load(resource.getInputStream());
return getReportCompiler().compileReport(design);
return JasperCompileManager.compileReport(design);
}
else {
throw new IllegalArgumentException(
@@ -549,8 +518,8 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* @see #getReportData
*/
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if (this.subReports != null) {
// Expose sub-reports as model attributes.
@@ -558,8 +527,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
// Transform any collections etc into JRDataSources for sub reports.
if (this.subReportDataKeys != null) {
for (int i = 0; i < this.subReportDataKeys.length; i++) {
String key = this.subReportDataKeys[i];
for (String key : this.subReportDataKeys) {
model.put(key, convertReportData(model.get(key)));
}
}
@@ -591,7 +559,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* @see net.sf.jasperreports.engine.JRParameter#REPORT_RESOURCE_BUNDLE
* @see org.springframework.web.servlet.support.JstlUtils#exposeLocalizationContext
*/
protected void exposeLocalizationContext(Map model, HttpServletRequest request) {
protected void exposeLocalizationContext(Map<String, Object> model, HttpServletRequest request) {
RequestContext rc = new RequestContext(request, getServletContext());
model.put(JRParameter.REPORT_LOCALE, rc.getLocale());
JasperReport report = getReport();
@@ -623,7 +591,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* @see #getReportData
* @see #setJdbcDataSource
*/
protected JasperPrint fillReport(Map model) throws Exception {
protected JasperPrint fillReport(Map<String, Object> model) throws Exception {
// Determine main report.
JasperReport report = getReport();
if (report == null) {
@@ -646,15 +614,14 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
}
else {
Collection values = model.values();
jrDataSource = (JRDataSource) CollectionUtils.findValueOfType(values, JRDataSource.class);
jrDataSource = CollectionUtils.findValueOfType(values, JRDataSource.class);
if (jrDataSource == null) {
JRDataSourceProvider provider =
(JRDataSourceProvider) CollectionUtils.findValueOfType(values, JRDataSourceProvider.class);
JRDataSourceProvider provider = CollectionUtils.findValueOfType(values, JRDataSourceProvider.class);
if (provider != null) {
jrDataSource = createReport(provider);
}
else {
jdbcDataSourceToUse = (DataSource) CollectionUtils.findValueOfType(values, DataSource.class);
jdbcDataSourceToUse = CollectionUtils.findValueOfType(values, DataSource.class);
if (jdbcDataSourceToUse == null) {
jdbcDataSourceToUse = this.jdbcDataSource;
}
@@ -689,12 +656,12 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
/**
* Fill the given report using the given JDBC DataSource and model.
*/
private JasperPrint doFillReport(JasperReport report, Map model, DataSource dataSource) throws Exception {
private JasperPrint doFillReport(JasperReport report, Map<String, Object> model, DataSource ds) throws Exception {
// Use the JDBC DataSource.
if (logger.isDebugEnabled()) {
logger.debug("Filling report using JDBC DataSource [" + dataSource + "]");
logger.debug("Filling report using JDBC DataSource [" + ds + "]");
}
Connection con = dataSource.getConnection();
Connection con = ds.getConnection();
try {
return JasperFillManager.fillReport(report, model, con);
}
@@ -747,7 +714,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* @see #convertReportData
* @see #getReportDataTypes
*/
protected JRDataSource getReportData(Map model) {
protected JRDataSource getReportData(Map<String, Object> model) {
// Try to find matching attribute, of given prioritized types.
Object value = CollectionUtils.findValueOfType(model.values(), getReportDataTypes());
return (value != null ? convertReportData(value) : null);
@@ -820,7 +787,7 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* @param model the map containing report parameters
* @throws Exception if post-processing failed
*/
protected void postProcessReport(JasperPrint populatedReport, Map model) throws Exception {
protected void postProcessReport(JasperPrint populatedReport, Map<String, Object> model) throws Exception {
}
/**
@@ -841,7 +808,8 @@ public abstract class AbstractJasperReportsView extends AbstractUrlBasedView {
* @see javax.servlet.ServletResponse#setContentType
* @see javax.servlet.ServletResponse#setCharacterEncoding
*/
protected abstract void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response)
protected abstract void renderReport(
JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response)
throws Exception;
}

View File

@@ -16,18 +16,15 @@
package org.springframework.web.servlet.view.jasperreports;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletResponse;
import net.sf.jasperreports.engine.JasperPrint;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContextException;
import org.springframework.util.ClassUtils;
import org.springframework.util.CollectionUtils;
/**
* Jasper Reports view class that allows for the actual rendering format to be
@@ -41,7 +38,7 @@ import org.springframework.util.ClassUtils;
* <code>Controller</code>:
*
* <pre>
* Map model = new HashMap();
* Map<String, Object> model = new HashMap<String, Object>();
* model.put("format", "pdf");</pre>
*
* Here <code>format</code> is the format key and <code>pdf</code> is
@@ -85,7 +82,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView {
* Stores the format mappings, with the format discriminator
* as key and the corresponding view class as value.
*/
private Map formatMappings;
private Map<String, Class> formatMappings;
/**
* Stores the mappings of mapping keys to Content-Disposition header values.
@@ -98,7 +95,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView {
* with a default set of mappings.
*/
public JasperReportsMultiFormatView() {
this.formatMappings = new HashMap(4);
this.formatMappings = new HashMap<String, Class>(4);
this.formatMappings.put("csv", JasperReportsCsvView.class);
this.formatMappings.put("html", JasperReportsHtmlView.class);
this.formatMappings.put("pdf", JasperReportsPdfView.class);
@@ -123,26 +120,11 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView {
* <li><code>xls</code> - <code>JasperReportsXlsView</code></li>
* </ul>
*/
public void setFormatMappings(Properties mappingsWithClassNames) {
if (mappingsWithClassNames == null || mappingsWithClassNames.isEmpty()) {
throw new IllegalArgumentException("formatMappings must not be empty");
}
this.formatMappings = new HashMap(mappingsWithClassNames.size());
for (Enumeration discriminators = mappingsWithClassNames.propertyNames(); discriminators.hasMoreElements();) {
String discriminator = (String) discriminators.nextElement();
String className = mappingsWithClassNames.getProperty(discriminator);
try {
if (logger.isDebugEnabled()) {
logger.debug("Mapped view class [" + className + "] to mapping key [" + discriminator + "]");
}
this.formatMappings.put(discriminator, ClassUtils.forName(className));
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException(
"Class [" + className + "] mapped to format [" + discriminator + "] cannot be found", ex);
}
public void setFormatMappings(Map<String, Class> formatMappings) {
if (CollectionUtils.isEmpty(formatMappings)) {
throw new IllegalArgumentException("'formatMappings' must not be empty");
}
this.formatMappings = formatMappings;
}
/**
@@ -179,7 +161,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView {
* report is then delegated to an instance of that view class.
*/
@Override
protected void renderReport(JasperPrint populatedReport, Map model, HttpServletResponse response)
protected void renderReport(JasperPrint populatedReport, Map<String, Object> model, HttpServletResponse response)
throws Exception {
String format = (String) model.get(this.formatKey);
@@ -191,7 +173,7 @@ public class JasperReportsMultiFormatView extends AbstractJasperReportsView {
logger.debug("Rendering report using format mapping key [" + format + "]");
}
Class viewClass = (Class) this.formatMappings.get(format);
Class viewClass = this.formatMappings.get(format);
if (viewClass == null) {
throw new IllegalArgumentException("Format discriminator [" + format + "] is not a configured mapping");
}

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2005 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.web.servlet.view.jasperreports;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import javax.sql.DataSource;
import net.sf.jasperreports.engine.design.JRCompiler;
@@ -45,7 +44,7 @@ public class JasperReportsViewResolver extends UrlBasedViewResolver {
private Properties headers;
private Map exporterParameters = new HashMap();
private Map<String, Object> exporterParameters = new HashMap<String, Object>();
private DataSource jdbcDataSource;
@@ -96,7 +95,7 @@ public class JasperReportsViewResolver extends UrlBasedViewResolver {
* Set the <code>exporterParameters</code> the view class should use.
* @see AbstractJasperReportsView#setExporterParameters
*/
public void setExporterParameters(Map exporterParameters) {
public void setExporterParameters(Map<String, Object> exporterParameters) {
this.exporterParameters = exporterParameters;
}
@@ -108,30 +107,16 @@ public class JasperReportsViewResolver extends UrlBasedViewResolver {
this.jdbcDataSource = jdbcDataSource;
}
/**
* Set the {@link JRCompiler} the view class should use.
* @see AbstractJasperReportsView#setReportCompiler
*/
public void setReportCompiler(JRCompiler reportCompiler) {
this.reportCompiler = reportCompiler;
}
@Override
protected AbstractUrlBasedView buildView(String viewName) throws Exception {
AbstractJasperReportsView view = (AbstractJasperReportsView) super.buildView(viewName);
view.setReportDataKey(this.reportDataKey);
view.setSubReportUrls(this.subReportUrls);
view.setSubReportDataKeys(this.subReportDataKeys);
view.setHeaders(this.headers);
view.setExporterParameters(this.exporterParameters);
view.setJdbcDataSource(this.jdbcDataSource);
if (this.reportCompiler != null) {
view.setReportCompiler(this.reportCompiler);
}
return view;
}

View File

@@ -50,8 +50,8 @@ import org.springframework.web.util.WebUtils;
public class TilesView extends AbstractUrlBasedView {
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
ServletContext servletContext = getServletContext();
TilesContainer container = TilesAccess.getContainer(servletContext);
@@ -73,7 +73,7 @@ public class TilesView extends AbstractUrlBasedView {
}
}
container.render(getUrl(), new Object[] {request, response});
container.render(getUrl(), request, response);
}
}

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.
@@ -27,7 +27,6 @@ import org.apache.velocity.context.Context;
import org.apache.velocity.tools.view.ToolboxManager;
import org.apache.velocity.tools.view.context.ChainedContext;
import org.apache.velocity.tools.view.servlet.ServletToolboxManager;
import org.apache.velocity.tools.view.tools.ViewTool;
import org.springframework.util.ClassUtils;
import org.springframework.util.ReflectionUtils;
@@ -56,7 +55,7 @@ import org.springframework.util.ReflectionUtils;
*
* <p>This is a separate class mainly to avoid a required dependency on
* the view package of Velocity Tools in {@link VelocityView} itself.
* As of Spring 2.0, this class requires Velocity Tools 1.2 or higher.
* As of Spring 3.0, this class requires Velocity Tools 1.3 or higher.
*
* @author Juergen Hoeller
* @since 1.1.3
@@ -64,7 +63,6 @@ import org.springframework.util.ReflectionUtils;
* @see #initTool
* @see org.apache.velocity.tools.view.context.ViewContext
* @see org.apache.velocity.tools.view.context.ChainedContext
* @see org.apache.velocity.tools.view.tools.ViewTool
* @see org.apache.velocity.tools.view.tools.LinkTool
*/
public class VelocityToolboxView extends VelocityView {
@@ -102,7 +100,7 @@ public class VelocityToolboxView extends VelocityView {
*/
@Override
protected Context createVelocityContext(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
// Create a ChainedContext instance.
ChainedContext velocityContext = new ChainedContext(
@@ -123,26 +121,14 @@ public class VelocityToolboxView extends VelocityView {
* Overridden to check for the ViewContext interface which is part of the
* view package of Velocity Tools. This requires a special Velocity context,
* like ChainedContext as set up by {@link #createVelocityContext} in this class.
* @see org.apache.velocity.tools.view.tools.ViewTool#init(Object)
* @see org.apache.velocity.tools.view.tools.LinkTool#init(Object)
*/
@Override
protected void initTool(Object tool, Context velocityContext) throws Exception {
// Initialize ViewTool instances with the Velocity context.
// Despite having an "init(Object)" method, all known ViewTool
// implementations expect a ViewContext implementation as argument.
// ChainedContext implements the ViewContext interface.
if (tool instanceof ViewTool) {
// Velocity Tools 1.2: an actual ViewTool implementation.
((ViewTool) tool).init(velocityContext);
}
else {
// Velocity Tools 1.3: a class-level "init(Object)" method.
Method initMethod =
ClassUtils.getMethodIfAvailable(tool.getClass(), "init", new Class[] {Object.class});
if (initMethod != null) {
ReflectionUtils.invokeMethod(initMethod, tool, new Object[] {velocityContext});
}
// Velocity Tools 1.3: a class-level "init(Object)" method.
Method initMethod = ClassUtils.getMethodIfAvailable(tool.getClass(), "init", Object.class);
if (initMethod != null) {
ReflectionUtils.invokeMethod(initMethod, tool, new Object[] {velocityContext});
}
}

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,20 +16,14 @@
package org.springframework.web.servlet.view.velocity;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.app.tools.VelocityFormatter;
import org.apache.velocity.context.Context;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ResourceNotFoundException;
@@ -40,7 +34,6 @@ import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactoryUtils;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContextException;
import org.springframework.util.ClassUtils;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.AbstractTemplateView;
import org.springframework.web.util.NestedServletException;
@@ -90,9 +83,7 @@ import org.springframework.web.util.NestedServletException;
*/
public class VelocityView extends AbstractTemplateView {
private Map toolAttributes;
private String velocityFormatterAttribute;
private Map<String, Class> toolAttributes;
private String dateToolAttribute;
@@ -135,31 +126,8 @@ public class VelocityView extends AbstractTemplateView {
* @see #setDateToolAttribute
* @see #setNumberToolAttribute
*/
public void setToolAttributes(Properties toolAttributes) {
this.toolAttributes = new HashMap(toolAttributes.size());
for (Enumeration attributeNames = toolAttributes.propertyNames(); attributeNames.hasMoreElements();) {
String attributeName = (String) attributeNames.nextElement();
String className = toolAttributes.getProperty(attributeName);
Class toolClass = null;
try {
toolClass = ClassUtils.forName(className);
}
catch (ClassNotFoundException ex) {
throw new IllegalArgumentException(
"Invalid definition for tool '" + attributeName + "' - tool class not found: " + ex.getMessage());
}
this.toolAttributes.put(attributeName, toolClass);
}
}
/**
* Set the name of the VelocityFormatter helper object to expose in the
* Velocity context of this view, or <code>null</code> if not needed.
* <p>VelocityFormatter is part of the standard Velocity distribution.
* @see org.apache.velocity.app.tools.VelocityFormatter
*/
public void setVelocityFormatterAttribute(String velocityFormatterAttribute) {
this.velocityFormatterAttribute = velocityFormatterAttribute;
public void setToolAttributes(Map<String, Class> toolAttributes) {
this.toolAttributes = toolAttributes;
}
/**
@@ -269,9 +237,8 @@ public class VelocityView extends AbstractTemplateView {
*/
protected VelocityEngine autodetectVelocityEngine() throws BeansException {
try {
VelocityConfig velocityConfig = (VelocityConfig)
BeanFactoryUtils.beanOfTypeIncludingAncestors(
getApplicationContext(), VelocityConfig.class, true, false);
VelocityConfig velocityConfig = BeanFactoryUtils.beanOfTypeIncludingAncestors(
getApplicationContext(), VelocityConfig.class, true, false);
return velocityConfig.getVelocityEngine();
}
catch (NoSuchBeanDefinitionException ex) {
@@ -311,7 +278,7 @@ public class VelocityView extends AbstractTemplateView {
*/
@Override
protected void renderMergedTemplateModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
exposeHelpers(model, request);
@@ -332,7 +299,7 @@ public class VelocityView extends AbstractTemplateView {
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #renderMergedTemplateModel
*/
protected void exposeHelpers(Map model, HttpServletRequest request) throws Exception {
protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
}
/**
@@ -356,7 +323,7 @@ public class VelocityView extends AbstractTemplateView {
* @see VelocityToolboxView
*/
protected Context createVelocityContext(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
return createVelocityContext(model);
}
@@ -372,7 +339,7 @@ public class VelocityView extends AbstractTemplateView {
* @throws Exception if there's a fatal error while creating the context
* @see org.apache.velocity.VelocityContext
*/
protected Context createVelocityContext(Map model) throws Exception {
protected Context createVelocityContext(Map<String, Object> model) throws Exception {
return new VelocityContext(model);
}
@@ -415,7 +382,6 @@ public class VelocityView extends AbstractTemplateView {
* @param velocityContext Velocity context that will be passed to the template
* @param request current HTTP request
* @throws Exception if there's a fatal error while we're adding model attributes
* @see #setVelocityFormatterAttribute
* @see #setDateToolAttribute
* @see #setNumberToolAttribute
* @see #exposeHelpers(Map, HttpServletRequest)
@@ -424,10 +390,9 @@ public class VelocityView extends AbstractTemplateView {
protected void exposeToolAttributes(Context velocityContext, HttpServletRequest request) throws Exception {
// Expose generic attributes.
if (this.toolAttributes != null) {
for (Iterator it = this.toolAttributes.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
String attributeName = (String) entry.getKey();
Class toolClass = (Class) entry.getValue();
for (Map.Entry<String, Class> entry : this.toolAttributes.entrySet()) {
String attributeName = entry.getKey();
Class toolClass = entry.getValue();
try {
Object tool = toolClass.newInstance();
initTool(tool, velocityContext);
@@ -439,11 +404,6 @@ public class VelocityView extends AbstractTemplateView {
}
}
// Expose VelocityFormatter attribute.
if (this.velocityFormatterAttribute != null) {
velocityContext.put(this.velocityFormatterAttribute, new VelocityFormatter(velocityContext));
}
// Expose locale-aware DateTool/NumberTool attributes.
if (this.dateToolAttribute != null || this.numberToolAttribute != null) {
Locale locale = RequestContextUtils.getLocale(request);

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.
@@ -20,8 +20,8 @@ import org.springframework.web.servlet.view.AbstractTemplateViewResolver;
import org.springframework.web.servlet.view.AbstractUrlBasedView;
/**
* Convenience subclass of UrlBasedViewResolver that supports VelocityView
* (that is Velocity templates) and custom subclasses of it.
* Convenience subclass of {@link org.springframework.web.servlet.view.UrlBasedViewResolver}
* that supports VelocityView (i.e. Velocity templates) and custom subclasses of it.
*
* <p>The view class for all views generated by this resolver can be specified
* via <code>setViewClass</code>. See UrlBasedViewResolver's javadoc for details.
@@ -44,8 +44,6 @@ import org.springframework.web.servlet.view.AbstractUrlBasedView;
*/
public class VelocityViewResolver extends AbstractTemplateViewResolver {
private String velocityFormatterAttribute;
private String dateToolAttribute;
private String numberToolAttribute;
@@ -71,17 +69,6 @@ public class VelocityViewResolver extends AbstractTemplateViewResolver {
return VelocityView.class;
}
/**
* Set the name of the VelocityFormatter helper object to expose in the
* Velocity context of this view, or <code>null</code> if not needed.
* VelocityFormatter is part of the standard Velocity distribution.
* @see org.apache.velocity.app.tools.VelocityFormatter
* @see VelocityView#setVelocityFormatterAttribute
*/
public void setVelocityFormatterAttribute(String velocityFormatterAttribute) {
this.velocityFormatterAttribute = velocityFormatterAttribute;
}
/**
* Set the name of the DateTool helper object to expose in the Velocity context
* of this view, or <code>null</code> if not needed. DateTool is part of Velocity Tools 1.0.
@@ -143,7 +130,6 @@ public class VelocityViewResolver extends AbstractTemplateViewResolver {
@Override
protected AbstractUrlBasedView buildView(String viewName) throws Exception {
VelocityView view = (VelocityView) super.buildView(viewName);
view.setVelocityFormatterAttribute(this.velocityFormatterAttribute);
view.setDateToolAttribute(this.dateToolAttribute);
view.setNumberToolAttribute(this.numberToolAttribute);
if (this.toolboxConfigLocation != null) {

View File

@@ -20,10 +20,8 @@ import java.io.BufferedOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.ErrorListener;
@@ -320,7 +318,7 @@ public abstract class AbstractXsltView extends AbstractView {
@Override
protected final void renderMergedOutputModel(
Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
@@ -330,7 +328,7 @@ public abstract class AbstractXsltView extends AbstractView {
Object singleModel = null;
if (this.useSingleModelNameAsRoot && model.size() == 1) {
docRoot = (String) model.keySet().iterator().next();
docRoot = model.keySet().iterator().next();
if (logger.isDebugEnabled()) {
logger.debug("Single model object received, key [" + docRoot + "] will be used as root tag");
}
@@ -370,7 +368,7 @@ public abstract class AbstractXsltView extends AbstractView {
* @throws Exception if an error occurs
*/
protected Source createXsltSource(
Map model, String root, HttpServletRequest request, HttpServletResponse response)
Map<String, Object> model, String root, HttpServletRequest request, HttpServletResponse response)
throws Exception {
return null;
@@ -393,10 +391,10 @@ public abstract class AbstractXsltView extends AbstractView {
* @see #useWriter()
*/
protected void doTransform(
Map model, Source source, HttpServletRequest request, HttpServletResponse response)
Map<String, Object> model, Source source, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Map parameters = getParameters(model, request);
Map<String, Object> parameters = getParameters(model, request);
Result result = (useWriter() ?
new StreamResult(response.getWriter()) :
new StreamResult(new BufferedOutputStream(response.getOutputStream())));
@@ -416,7 +414,7 @@ public abstract class AbstractXsltView extends AbstractView {
* @see #getParameters()
* @see javax.xml.transform.Transformer#setParameter
*/
protected Map getParameters(Map model, HttpServletRequest request) {
protected Map getParameters(Map<String, Object> model, HttpServletRequest request) {
return getParameters(request);
}
@@ -424,25 +422,13 @@ public abstract class AbstractXsltView extends AbstractView {
* Return a Map of transformer parameters to be applied to the stylesheet.
* <p>Subclasses can override this method in order to apply one or more
* parameters to the transformation process.
* <p>The default implementation delegates to the simple
* {@link #getParameters()} variant.
* <p>The default implementation simply returns <code>null</code>.
* @param request current HTTP request
* @return a Map of parameters to apply to the transformation process
* @see #getParameters(Map, HttpServletRequest)
* @see javax.xml.transform.Transformer#setParameter
*/
protected Map getParameters(HttpServletRequest request) {
return getParameters();
}
/**
* Return a Map of transformer parameters to be applied to the stylesheet.
* @return a Map of parameters to apply to the transformation process
* @deprecated as of Spring 2.0.4, in favor of the
* {@link #getParameters(HttpServletRequest)} variant
*/
@Deprecated
protected Map getParameters() {
return null;
}
@@ -471,7 +457,7 @@ public abstract class AbstractXsltView extends AbstractView {
* @param encoding the preferred character encoding that the underlying Transformer should use
* @throws Exception if an error occurs
*/
protected void doTransform(Source source, Map parameters, Result result, String encoding)
protected void doTransform(Source source, Map<String, Object> parameters, Result result, String encoding)
throws Exception {
try {
@@ -519,7 +505,7 @@ public abstract class AbstractXsltView extends AbstractView {
* @throws TransformerConfigurationException if the Transformer object
* could not be built
*/
protected Transformer buildTransformer(Map parameters) throws TransformerConfigurationException {
protected Transformer buildTransformer(Map<String, Object> parameters) throws TransformerConfigurationException {
Templates templates = getTemplates();
Transformer transformer =
(templates != null ? templates.newTransformer() : getTransformerFactory().newTransformer());
@@ -562,11 +548,10 @@ public abstract class AbstractXsltView extends AbstractView {
* (as determined by {@link #getParameters(Map, HttpServletRequest)})
* @param transformer the Transformer to aply the parameters
*/
protected void applyTransformerParameters(Map parameters, Transformer transformer) {
protected void applyTransformerParameters(Map<String, Object> parameters, Transformer transformer) {
if (parameters != null) {
for (Iterator it = parameters.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry) it.next();
transformer.setParameter(entry.getKey().toString(), entry.getValue());
for (Map.Entry<String, Object> entry : parameters.entrySet()) {
transformer.setParameter(entry.getKey(), entry.getValue());
}
}
}

View File

@@ -20,10 +20,8 @@ import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.ErrorListener;
@@ -48,7 +46,6 @@ import org.springframework.context.ApplicationContextException;
import org.springframework.core.io.Resource;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.util.xml.SimpleTransformErrorListener;
import org.springframework.util.xml.TransformerUtils;
@@ -222,7 +219,8 @@ public class XsltView extends AbstractUrlBasedView {
@Override
protected void renderMergedOutputModel(Map model, HttpServletRequest request, HttpServletResponse response)
protected void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception {
Templates templates = this.cachedTemplates;
@@ -270,7 +268,7 @@ public class XsltView extends AbstractUrlBasedView {
* @see #setSourceKey
* @see #convertSource
*/
protected Source locateSource(Map model) throws Exception {
protected Source locateSource(Map<String, Object> model) throws Exception {
if (this.sourceKey != null) {
return convertSource(model.get(this.sourceKey));
}
@@ -335,7 +333,7 @@ public class XsltView extends AbstractUrlBasedView {
* @see #copyOutputProperties(Transformer)
* @see #configureIndentation(Transformer)
*/
protected void configureTransformer(Map model, HttpServletResponse response, Transformer transformer) {
protected void configureTransformer(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
copyModelParameters(model, transformer);
copyOutputProperties(transformer);
configureIndentation(transformer);
@@ -379,8 +377,10 @@ public class XsltView extends AbstractUrlBasedView {
* @param model merged output Map (never <code>null</code>)
* @param transformer the target transformer
*/
protected final void copyModelParameters(Map model, Transformer transformer) {
copyMapEntriesToTransformerParameters(model, transformer);
protected final void copyModelParameters(Map<String, Object> model, Transformer transformer) {
for (Map.Entry<String, Object> entry : model.entrySet()) {
transformer.setParameter(entry.getKey(), entry.getValue());
}
}
/**
@@ -394,7 +394,7 @@ public class XsltView extends AbstractUrlBasedView {
* @param response current HTTP response
* @param transformer the target transformer
*/
protected void configureResponse(Map model, HttpServletResponse response, Transformer transformer) {
protected void configureResponse(Map<String, Object> model, HttpServletResponse response, Transformer transformer) {
String contentType = getContentType();
String mediaType = transformer.getOutputProperty(OutputKeys.MEDIA_TYPE);
String encoding = transformer.getOutputProperty(OutputKeys.ENCODING);
@@ -403,7 +403,7 @@ public class XsltView extends AbstractUrlBasedView {
}
if (StringUtils.hasText(encoding)) {
// Only apply encoding if content type is specified but does not contain charset clause already.
if (contentType != null && contentType.toLowerCase().indexOf(WebUtils.CONTENT_TYPE_CHARSET_PREFIX) == -1) {
if (contentType != null && !contentType.toLowerCase().contains(WebUtils.CONTENT_TYPE_CHARSET_PREFIX)) {
contentType = contentType + WebUtils.CONTENT_TYPE_CHARSET_PREFIX + encoding;
}
}
@@ -464,18 +464,6 @@ public class XsltView extends AbstractUrlBasedView {
}
}
/**
* Copy all {@link Map.Entry entries} from the supplied {@link Map} into the
* {@link Transformer#setParameter(String, Object) parameter set} of the supplied
* {@link Transformer}.
*/
private void copyMapEntriesToTransformerParameters(Map map, Transformer transformer) {
for (Iterator iterator = map.entrySet().iterator(); iterator.hasNext();) {
Map.Entry entry = (Map.Entry) iterator.next();
transformer.setParameter(ObjectUtils.nullSafeToString(entry.getKey()), entry.getValue());
}
}
/**
* Close the underlying resource managed by the supplied {@link Source} if applicable.
* <p>Only works for {@link StreamSource StreamSources}.
@@ -489,6 +477,7 @@ public class XsltView extends AbstractUrlBasedView {
streamSource.getReader().close();
}
catch (IOException ex) {
// ignore
}
}
if (streamSource.getInputStream() != null) {
@@ -496,6 +485,7 @@ public class XsltView extends AbstractUrlBasedView {
streamSource.getInputStream().close();
}
catch (IOException ex) {
// ignore
}
}
}