Convert CRLF (dos) to LF (unix)

Prior to this change, roughly 5% (~300 out of 6000+) of files under the
source tree had CRLF line endings as opposed to the majority which have
LF endings.

This change normalizes these files to LF for consistency going forward.

Command used:

$ git ls-files | xargs file | grep CRLF | cut -d":" -f1 | xargs dos2unix

Issue: SPR-5608
This commit is contained in:
Chris Beams
2011-12-21 14:40:03 +01:00
parent 096de373b4
commit ae72cf2f50
292 changed files with 30756 additions and 30756 deletions

View File

@@ -1,50 +1,50 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;
/**
* {@link java.beans.PropertyEditor Editor} for {@link MediaType}
* descriptors, to automatically convert <code>String</code> specifications
* (e.g. <code>"text/html"</code>) to <code>MediaType</code> properties.
*
* @author Juergen Hoeller
* @since 3.0
* @see MediaType
*/
public class MediaTypeEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
if (StringUtils.hasText(text)) {
setValue(MediaType.parseMediaType(text));
}
else {
setValue(null);
}
}
@Override
public String getAsText() {
MediaType mediaType = (MediaType) getValue();
return (mediaType != null ? mediaType.toString() : "");
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http;
import java.beans.PropertyEditorSupport;
import org.springframework.util.StringUtils;
/**
* {@link java.beans.PropertyEditor Editor} for {@link MediaType}
* descriptors, to automatically convert <code>String</code> specifications
* (e.g. <code>"text/html"</code>) to <code>MediaType</code> properties.
*
* @author Juergen Hoeller
* @since 3.0
* @see MediaType
*/
public class MediaTypeEditor extends PropertyEditorSupport {
@Override
public void setAsText(String text) {
if (StringUtils.hasText(text)) {
setValue(MediaType.parseMediaType(text));
}
else {
setValue(null);
}
}
@Override
public String getAsText() {
MediaType mediaType = (MediaType) getValue();
return (mediaType != null ? mediaType.toString() : "");
}
}

View File

@@ -1,35 +1,35 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter.xml;
import org.springframework.http.converter.FormHttpMessageConverter;
/**
* Extension of {@link org.springframework.http.converter.FormHttpMessageConverter},
* adding support for XML-based parts through a {@link SourceHttpMessageConverter}.
*
* @author Juergen Hoeller
* @since 3.0.3
*/
public class XmlAwareFormHttpMessageConverter extends FormHttpMessageConverter {
public XmlAwareFormHttpMessageConverter() {
super();
addPartConverter(new SourceHttpMessageConverter());
}
}
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.http.converter.xml;
import org.springframework.http.converter.FormHttpMessageConverter;
/**
* Extension of {@link org.springframework.http.converter.FormHttpMessageConverter},
* adding support for XML-based parts through a {@link SourceHttpMessageConverter}.
*
* @author Juergen Hoeller
* @since 3.0.3
*/
public class XmlAwareFormHttpMessageConverter extends FormHttpMessageConverter {
public XmlAwareFormHttpMessageConverter() {
super();
addPartConverter(new SourceHttpMessageConverter());
}
}

View File

@@ -1,88 +1,88 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind;
import java.util.Iterator;
import java.util.Map;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* {@link ServletRequestBindingException} subclass that indicates an unsatisfied
* parameter condition, as typically expressed using an <code>@RequestMapping</code>
* annotation at the <code>@Controller</code> type level.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
public class UnsatisfiedServletRequestParameterException extends ServletRequestBindingException {
private final String[] paramConditions;
private final Map<String, String[]> actualParams;
/**
* Create a new UnsatisfiedServletRequestParameterException.
* @param paramConditions the parameter conditions that have been violated
* @param actualParams the actual parameter Map associated with the ServletRequest
*/
@SuppressWarnings("unchecked")
public UnsatisfiedServletRequestParameterException(String[] paramConditions, Map actualParams) {
super("");
this.paramConditions = paramConditions;
this.actualParams = (Map<String, String[]>) actualParams;
}
@Override
public String getMessage() {
return "Parameter conditions \"" + StringUtils.arrayToDelimitedString(this.paramConditions, ", ") +
"\" not met for actual request parameters: " + requestParameterMapToString(this.actualParams);
}
private static String requestParameterMapToString(Map<String, String[]> actualParams) {
StringBuilder result = new StringBuilder();
for (Iterator<Map.Entry<String, String[]>> it = actualParams.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String[]> entry = it.next();
result.append(entry.getKey()).append('=').append(ObjectUtils.nullSafeToString(entry.getValue()));
if (it.hasNext()) {
result.append(", ");
}
}
return result.toString();
}
/**
* Return the parameter conditions that have been violated.
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
public final String[] getParamConditions() {
return this.paramConditions;
}
/**
* Return the actual parameter Map associated with the ServletRequest.
* @see javax.servlet.ServletRequest#getParameterMap()
*/
public final Map<String, String[]> getActualParams() {
return this.actualParams;
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind;
import java.util.Iterator;
import java.util.Map;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
/**
* {@link ServletRequestBindingException} subclass that indicates an unsatisfied
* parameter condition, as typically expressed using an <code>@RequestMapping</code>
* annotation at the <code>@Controller</code> type level.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
public class UnsatisfiedServletRequestParameterException extends ServletRequestBindingException {
private final String[] paramConditions;
private final Map<String, String[]> actualParams;
/**
* Create a new UnsatisfiedServletRequestParameterException.
* @param paramConditions the parameter conditions that have been violated
* @param actualParams the actual parameter Map associated with the ServletRequest
*/
@SuppressWarnings("unchecked")
public UnsatisfiedServletRequestParameterException(String[] paramConditions, Map actualParams) {
super("");
this.paramConditions = paramConditions;
this.actualParams = (Map<String, String[]>) actualParams;
}
@Override
public String getMessage() {
return "Parameter conditions \"" + StringUtils.arrayToDelimitedString(this.paramConditions, ", ") +
"\" not met for actual request parameters: " + requestParameterMapToString(this.actualParams);
}
private static String requestParameterMapToString(Map<String, String[]> actualParams) {
StringBuilder result = new StringBuilder();
for (Iterator<Map.Entry<String, String[]>> it = actualParams.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, String[]> entry = it.next();
result.append(entry.getKey()).append('=').append(ObjectUtils.nullSafeToString(entry.getValue()));
if (it.hasNext()) {
result.append(", ");
}
}
return result.toString();
}
/**
* Return the parameter conditions that have been violated.
* @see org.springframework.web.bind.annotation.RequestMapping#params()
*/
public final String[] getParamConditions() {
return this.paramConditions;
}
/**
* Return the actual parameter Map associated with the ServletRequest.
* @see javax.servlet.ServletRequest#getParameterMap()
*/
public final Map<String, String[]> getActualParams() {
return this.actualParams;
}
}

View File

@@ -1,35 +1,35 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Meta annotation that indicates a web mapping annotation.
*
* @author Juergen Hoeller
* @since 3.0
* @see RequestMapping
*/
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* Meta annotation that indicates a web mapping annotation.
*
* @author Juergen Hoeller
* @since 3.0
* @see RequestMapping
*/
@Target({ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface Mapping {
}

View File

@@ -1,38 +1,38 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
/**
* Common value constants shared between bind annotations.
*
* @author Juergen Hoeller
* @since 3.0.1
*/
public interface ValueConstants {
/**
* Constant defining a value for no default - as a replacement for
* <code>null</code> which we cannot use in annotation attributes.
* <p>This is an artificial arrangement of 16 unicode characters,
* with its sole purpose being to never match user-declared values.
* @see RequestParam#defaultValue()
* @see RequestHeader#defaultValue()
* @see CookieValue#defaultValue()
*/
String DEFAULT_NONE = "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n";
}
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.bind.annotation;
/**
* Common value constants shared between bind annotations.
*
* @author Juergen Hoeller
* @since 3.0.1
*/
public interface ValueConstants {
/**
* Constant defining a value for no default - as a replacement for
* <code>null</code> which we cannot use in annotation attributes.
* <p>This is an artificial arrangement of 16 unicode characters,
* with its sole purpose being to never match user-declared values.
* @see RequestParam#defaultValue()
* @see RequestHeader#defaultValue()
* @see CookieValue#defaultValue()
*/
String DEFAULT_NONE = "\n\t\t\n\t\t\n\uE000\uE001\uE002\n\t\t\t\t\n";
}

View File

@@ -1,77 +1,77 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
/**
* Web application listener that cleans up remaining disposable attributes
* in the ServletContext, i.e. attributes which implement {@link DisposableBean}
* and haven't been removed before. This is typically used for destroying objects
* in "application" scope, for which the lifecycle implies destruction at the
* very end of the web application's shutdown phase.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.context.support.ServletContextScope
* @see ContextLoaderListener
*/
public class ContextCleanupListener implements ServletContextListener {
private static final Log logger = LogFactory.getLog(ContextCleanupListener.class);
public void contextInitialized(ServletContextEvent event) {
}
public void contextDestroyed(ServletContextEvent event) {
cleanupAttributes(event.getServletContext());
}
/**
* Find all ServletContext attributes which implement {@link DisposableBean}
* and destroy them, removing all affected ServletContext attributes eventually.
* @param sc the ServletContext to check
*/
static void cleanupAttributes(ServletContext sc) {
Enumeration attrNames = sc.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (attrName.startsWith("org.springframework.")) {
Object attrValue = sc.getAttribute(attrName);
if (attrValue instanceof DisposableBean) {
try {
((DisposableBean) attrValue).destroy();
}
catch (Throwable ex) {
logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
}
}
}
}
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.DisposableBean;
/**
* Web application listener that cleans up remaining disposable attributes
* in the ServletContext, i.e. attributes which implement {@link DisposableBean}
* and haven't been removed before. This is typically used for destroying objects
* in "application" scope, for which the lifecycle implies destruction at the
* very end of the web application's shutdown phase.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.context.support.ServletContextScope
* @see ContextLoaderListener
*/
public class ContextCleanupListener implements ServletContextListener {
private static final Log logger = LogFactory.getLog(ContextCleanupListener.class);
public void contextInitialized(ServletContextEvent event) {
}
public void contextDestroyed(ServletContextEvent event) {
cleanupAttributes(event.getServletContext());
}
/**
* Find all ServletContext attributes which implement {@link DisposableBean}
* and destroy them, removing all affected ServletContext attributes eventually.
* @param sc the ServletContext to check
*/
static void cleanupAttributes(ServletContext sc) {
Enumeration attrNames = sc.getAttributeNames();
while (attrNames.hasMoreElements()) {
String attrName = (String) attrNames.nextElement();
if (attrName.startsWith("org.springframework.")) {
Object attrValue = sc.getAttribute(attrName);
if (attrValue instanceof DisposableBean) {
try {
((DisposableBean) attrValue).destroy();
}
catch (Throwable ex) {
logger.error("Couldn't invoke destroy method of attribute with name '" + attrName + "'", ex);
}
}
}
}
}
}

View File

@@ -1,54 +1,54 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.request;
import java.io.Serializable;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
/**
* Adapter that implements the Servlet 2.3 HttpSessionBindingListener
* interface, wrapping a session destruction callback.
*
* @author Juergen Hoeller
* @since 3.0
* @see RequestAttributes#registerDestructionCallback
* @see ServletRequestAttributes#registerSessionDestructionCallback
*/
public class DestructionCallbackBindingListener implements HttpSessionBindingListener, Serializable {
private final Runnable destructionCallback;
/**
* Create a new DestructionCallbackBindingListener for the given callback.
* @param destructionCallback the Runnable to execute when this listener
* object gets unbound from the session
*/
public DestructionCallbackBindingListener(Runnable destructionCallback) {
this.destructionCallback = destructionCallback;
}
public void valueBound(HttpSessionBindingEvent event) {
}
public void valueUnbound(HttpSessionBindingEvent event) {
this.destructionCallback.run();
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.request;
import java.io.Serializable;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
/**
* Adapter that implements the Servlet 2.3 HttpSessionBindingListener
* interface, wrapping a session destruction callback.
*
* @author Juergen Hoeller
* @since 3.0
* @see RequestAttributes#registerDestructionCallback
* @see ServletRequestAttributes#registerSessionDestructionCallback
*/
public class DestructionCallbackBindingListener implements HttpSessionBindingListener, Serializable {
private final Runnable destructionCallback;
/**
* Create a new DestructionCallbackBindingListener for the given callback.
* @param destructionCallback the Runnable to execute when this listener
* object gets unbound from the session
*/
public DestructionCallbackBindingListener(Runnable destructionCallback) {
this.destructionCallback = destructionCallback;
}
public void valueBound(HttpSessionBindingEvent event) {
}
public void valueUnbound(HttpSessionBindingEvent event) {
this.destructionCallback.run();
}
}

View File

@@ -1,111 +1,111 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.support;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.util.Assert;
/**
* {@link Scope} wrapper for a ServletContext, i.e. for global web application attributes.
*
* <p>This differs from traditional Spring singletons in that it exposes attributes in the
* ServletContext. Those attributes will get destroyed whenever the entire application
* shuts down, which might be earlier or later than the shutdown of the containing Spring
* ApplicationContext.
*
* <p>The associated destruction mechanism relies on a
* {@link org.springframework.web.context.ContextCleanupListener} being registered in
* <code>web.xml</code>. Note that {@link org.springframework.web.context.ContextLoaderListener}
* includes ContextCleanupListener's functionality.
*
* <p>This scope is registered as default scope with key
* {@link org.springframework.web.context.WebApplicationContext#SCOPE_APPLICATION "application"}.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.context.ContextCleanupListener
*/
public class ServletContextScope implements Scope, DisposableBean {
private final ServletContext servletContext;
private final Map<String, Runnable> destructionCallbacks = new LinkedHashMap<String, Runnable>();
/**
* Create a new Scope wrapper for the given ServletContext.
* @param servletContext the ServletContext to wrap
*/
public ServletContextScope(ServletContext servletContext) {
Assert.notNull(servletContext, "ServletContext must not be null");
this.servletContext = servletContext;
}
public Object get(String name, ObjectFactory<?> objectFactory) {
Object scopedObject = this.servletContext.getAttribute(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
this.servletContext.setAttribute(name, scopedObject);
}
return scopedObject;
}
public Object remove(String name) {
Object scopedObject = this.servletContext.getAttribute(name);
if (scopedObject != null) {
this.servletContext.removeAttribute(name);
this.destructionCallbacks.remove(name);
return scopedObject;
}
else {
return null;
}
}
public void registerDestructionCallback(String name, Runnable callback) {
this.destructionCallbacks.put(name, callback);
}
public Object resolveContextualObject(String key) {
return null;
}
public String getConversationId() {
return null;
}
/**
* Invoke all registered destruction callbacks.
* To be called on ServletContext shutdown.
* @see org.springframework.web.context.ContextCleanupListener
*/
public void destroy() {
for (Runnable runnable : this.destructionCallbacks.values()) {
runnable.run();
}
this.destructionCallbacks.clear();
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.support;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.util.Assert;
/**
* {@link Scope} wrapper for a ServletContext, i.e. for global web application attributes.
*
* <p>This differs from traditional Spring singletons in that it exposes attributes in the
* ServletContext. Those attributes will get destroyed whenever the entire application
* shuts down, which might be earlier or later than the shutdown of the containing Spring
* ApplicationContext.
*
* <p>The associated destruction mechanism relies on a
* {@link org.springframework.web.context.ContextCleanupListener} being registered in
* <code>web.xml</code>. Note that {@link org.springframework.web.context.ContextLoaderListener}
* includes ContextCleanupListener's functionality.
*
* <p>This scope is registered as default scope with key
* {@link org.springframework.web.context.WebApplicationContext#SCOPE_APPLICATION "application"}.
*
* @author Juergen Hoeller
* @since 3.0
* @see org.springframework.web.context.ContextCleanupListener
*/
public class ServletContextScope implements Scope, DisposableBean {
private final ServletContext servletContext;
private final Map<String, Runnable> destructionCallbacks = new LinkedHashMap<String, Runnable>();
/**
* Create a new Scope wrapper for the given ServletContext.
* @param servletContext the ServletContext to wrap
*/
public ServletContextScope(ServletContext servletContext) {
Assert.notNull(servletContext, "ServletContext must not be null");
this.servletContext = servletContext;
}
public Object get(String name, ObjectFactory<?> objectFactory) {
Object scopedObject = this.servletContext.getAttribute(name);
if (scopedObject == null) {
scopedObject = objectFactory.getObject();
this.servletContext.setAttribute(name, scopedObject);
}
return scopedObject;
}
public Object remove(String name) {
Object scopedObject = this.servletContext.getAttribute(name);
if (scopedObject != null) {
this.servletContext.removeAttribute(name);
this.destructionCallbacks.remove(name);
return scopedObject;
}
else {
return null;
}
}
public void registerDestructionCallback(String name, Runnable callback) {
this.destructionCallbacks.put(name, callback);
}
public Object resolveContextualObject(String key) {
return null;
}
public String getConversationId() {
return null;
}
/**
* Invoke all registered destruction callbacks.
* To be called on ServletContext shutdown.
* @see org.springframework.web.context.ContextCleanupListener
*/
public void destroy() {
for (Runnable runnable : this.destructionCallbacks.values()) {
runnable.run();
}
this.destructionCallbacks.clear();
}
}

View File

@@ -1,8 +1,8 @@
/**
*
* Support classes for annotation-based handler method processing.
*
*/
package org.springframework.web.method.annotation;
/**
*
* Support classes for annotation-based handler method processing.
*
*/
package org.springframework.web.method.annotation;

View File

@@ -1,8 +1,8 @@
/**
*
* Generic support classes for handler method processing.
*
*/
package org.springframework.web.method.support;
/**
*
* Generic support classes for handler method processing.
*
*/
package org.springframework.web.method.support;

View File

@@ -1,175 +1,175 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.multipart.support;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.springframework.http.HttpHeaders;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
/**
* Spring MultipartHttpServletRequest adapter, wrapping a Servlet 3.0 HttpServletRequest
* and its Part objects. Parameters get exposed through the native request's getParameter
* methods - without any custom processing on our side.
*
* @author Juergen Hoeller
* @since 3.1
*/
public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {
private static final String CONTENT_DISPOSITION = "Content-Disposition";
private static final String FILENAME_KEY = "filename=";
/**
* Create a new StandardMultipartHttpServletRequest wrapper for the given request.
* @param request the servlet request to wrap
* @throws MultipartException if parsing failed
*/
public StandardMultipartHttpServletRequest(HttpServletRequest request) throws MultipartException {
super(request);
try {
Collection<Part> parts = request.getParts();
MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
for (Part part : parts) {
String filename = extractFilename(part.getHeader(CONTENT_DISPOSITION));
if (filename != null) {
files.add(part.getName(), new StandardMultipartFile(part, filename));
}
}
setMultipartFiles(files);
}
catch (Exception ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
private String extractFilename(String contentDisposition) {
if (contentDisposition == null) {
return null;
}
// TODO: can only handle the typical case at the moment
int startIndex = contentDisposition.indexOf(FILENAME_KEY);
if (startIndex == -1) {
return null;
}
String filename = contentDisposition.substring(startIndex + FILENAME_KEY.length());
if (filename.startsWith("\"")) {
int endIndex = filename.indexOf("\"", 1);
if (endIndex != -1) {
return filename.substring(1, endIndex);
}
}
else {
int endIndex = filename.indexOf(";");
if (endIndex != -1) {
return filename.substring(0, endIndex);
}
}
return filename;
}
public String getMultipartContentType(String paramOrFileName) {
try {
Part part = getPart(paramOrFileName);
return (part != null ? part.getContentType() : null);
}
catch (Exception ex) {
throw new MultipartException("Could not access multipart servlet request", ex);
}
}
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
try {
Part part = getPart(paramOrFileName);
if (part != null) {
HttpHeaders headers = new HttpHeaders();
for (String headerName : part.getHeaderNames()) {
headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName)));
}
return headers;
}
else {
return null;
}
}
catch (Exception ex) {
throw new MultipartException("Could not access multipart servlet request", ex);
}
}
/**
* Spring MultipartFile adapter, wrapping a Servlet 3.0 Part object.
*/
private static class StandardMultipartFile implements MultipartFile {
private final Part part;
private final String filename;
public StandardMultipartFile(Part part, String filename) {
this.part = part;
this.filename = filename;
}
public String getName() {
return this.part.getName();
}
public String getOriginalFilename() {
return this.filename;
}
public String getContentType() {
return this.part.getContentType();
}
public boolean isEmpty() {
return (this.part.getSize() == 0);
}
public long getSize() {
return this.part.getSize();
}
public byte[] getBytes() throws IOException {
return FileCopyUtils.copyToByteArray(this.part.getInputStream());
}
public InputStream getInputStream() throws IOException {
return this.part.getInputStream();
}
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
}
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.multipart.support;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.springframework.http.HttpHeaders;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartFile;
/**
* Spring MultipartHttpServletRequest adapter, wrapping a Servlet 3.0 HttpServletRequest
* and its Part objects. Parameters get exposed through the native request's getParameter
* methods - without any custom processing on our side.
*
* @author Juergen Hoeller
* @since 3.1
*/
public class StandardMultipartHttpServletRequest extends AbstractMultipartHttpServletRequest {
private static final String CONTENT_DISPOSITION = "Content-Disposition";
private static final String FILENAME_KEY = "filename=";
/**
* Create a new StandardMultipartHttpServletRequest wrapper for the given request.
* @param request the servlet request to wrap
* @throws MultipartException if parsing failed
*/
public StandardMultipartHttpServletRequest(HttpServletRequest request) throws MultipartException {
super(request);
try {
Collection<Part> parts = request.getParts();
MultiValueMap<String, MultipartFile> files = new LinkedMultiValueMap<String, MultipartFile>(parts.size());
for (Part part : parts) {
String filename = extractFilename(part.getHeader(CONTENT_DISPOSITION));
if (filename != null) {
files.add(part.getName(), new StandardMultipartFile(part, filename));
}
}
setMultipartFiles(files);
}
catch (Exception ex) {
throw new MultipartException("Could not parse multipart servlet request", ex);
}
}
private String extractFilename(String contentDisposition) {
if (contentDisposition == null) {
return null;
}
// TODO: can only handle the typical case at the moment
int startIndex = contentDisposition.indexOf(FILENAME_KEY);
if (startIndex == -1) {
return null;
}
String filename = contentDisposition.substring(startIndex + FILENAME_KEY.length());
if (filename.startsWith("\"")) {
int endIndex = filename.indexOf("\"", 1);
if (endIndex != -1) {
return filename.substring(1, endIndex);
}
}
else {
int endIndex = filename.indexOf(";");
if (endIndex != -1) {
return filename.substring(0, endIndex);
}
}
return filename;
}
public String getMultipartContentType(String paramOrFileName) {
try {
Part part = getPart(paramOrFileName);
return (part != null ? part.getContentType() : null);
}
catch (Exception ex) {
throw new MultipartException("Could not access multipart servlet request", ex);
}
}
public HttpHeaders getMultipartHeaders(String paramOrFileName) {
try {
Part part = getPart(paramOrFileName);
if (part != null) {
HttpHeaders headers = new HttpHeaders();
for (String headerName : part.getHeaderNames()) {
headers.put(headerName, new ArrayList<String>(part.getHeaders(headerName)));
}
return headers;
}
else {
return null;
}
}
catch (Exception ex) {
throw new MultipartException("Could not access multipart servlet request", ex);
}
}
/**
* Spring MultipartFile adapter, wrapping a Servlet 3.0 Part object.
*/
private static class StandardMultipartFile implements MultipartFile {
private final Part part;
private final String filename;
public StandardMultipartFile(Part part, String filename) {
this.part = part;
this.filename = filename;
}
public String getName() {
return this.part.getName();
}
public String getOriginalFilename() {
return this.filename;
}
public String getContentType() {
return this.part.getContentType();
}
public boolean isEmpty() {
return (this.part.getSize() == 0);
}
public long getSize() {
return this.part.getSize();
}
public byte[] getBytes() throws IOException {
return FileCopyUtils.copyToByteArray(this.part.getInputStream());
}
public InputStream getInputStream() throws IOException {
return this.part.getInputStream();
}
public void transferTo(File dest) throws IOException, IllegalStateException {
this.part.write(dest.getPath());
}
}
}

View File

@@ -1,73 +1,73 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.multipart.support;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
/**
* Standard implementation of the {@link MultipartResolver} interface,
* based on the Servlet 3.0 {@link javax.servlet.http.Part} API.
* To be added as "multipartResolver" bean to a Spring DispatcherServlet context,
* without any extra configuration at the bean level (see below).
*
* <p><b>Note:</b> In order to use Servlet 3.0 based multipart parsing,
* you need to mark the affected servlet with a "multipart-config" section in
* <code>web.xml</code>, or with a {@link javax.servlet.MultipartConfigElement}
* in programmatic servlet registration, or (in case of a custom servlet class)
* possibly with a {@link javax.servlet.annotation.MultipartConfig} annotation
* on your servlet class. Configuration settings such as maximum sizes or
* storage locations need to be applied at that servlet registration level;
* Servlet 3.0 does not allow for them to be set at the MultipartResolver level.
*
* @author Juergen Hoeller
* @since 3.1
*/
public class StandardServletMultipartResolver implements MultipartResolver {
public boolean isMultipart(HttpServletRequest request) {
// Same check as in Commons FileUpload...
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
}
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
return new StandardMultipartHttpServletRequest(request);
}
public void cleanupMultipart(MultipartHttpServletRequest request) {
// To be on the safe side: explicitly delete all parts.
try {
for (Part part : request.getParts()) {
part.delete();
}
}
catch (Exception ex) {
LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
}
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.multipart.support;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.multipart.MultipartException;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
/**
* Standard implementation of the {@link MultipartResolver} interface,
* based on the Servlet 3.0 {@link javax.servlet.http.Part} API.
* To be added as "multipartResolver" bean to a Spring DispatcherServlet context,
* without any extra configuration at the bean level (see below).
*
* <p><b>Note:</b> In order to use Servlet 3.0 based multipart parsing,
* you need to mark the affected servlet with a "multipart-config" section in
* <code>web.xml</code>, or with a {@link javax.servlet.MultipartConfigElement}
* in programmatic servlet registration, or (in case of a custom servlet class)
* possibly with a {@link javax.servlet.annotation.MultipartConfig} annotation
* on your servlet class. Configuration settings such as maximum sizes or
* storage locations need to be applied at that servlet registration level;
* Servlet 3.0 does not allow for them to be set at the MultipartResolver level.
*
* @author Juergen Hoeller
* @since 3.1
*/
public class StandardServletMultipartResolver implements MultipartResolver {
public boolean isMultipart(HttpServletRequest request) {
// Same check as in Commons FileUpload...
if (!"post".equals(request.getMethod().toLowerCase())) {
return false;
}
String contentType = request.getContentType();
return (contentType != null && contentType.toLowerCase().startsWith("multipart/"));
}
public MultipartHttpServletRequest resolveMultipart(HttpServletRequest request) throws MultipartException {
return new StandardMultipartHttpServletRequest(request);
}
public void cleanupMultipart(MultipartHttpServletRequest request) {
// To be on the safe side: explicitly delete all parts.
try {
for (Part part : request.getParts()) {
part.delete();
}
}
catch (Exception ex) {
LogFactory.getLog(getClass()).warn("Failed to perform cleanup of multipart items", ex);
}
}
}

View File

@@ -1,66 +1,66 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletInputStream;
import org.springframework.util.Assert;
/**
* Delegating implementation of {@link javax.servlet.ServletInputStream}.
*
* <p>Used by {@link MockHttpServletRequest}; typically not directly
* used for testing application controllers.
*
* @author Juergen Hoeller
* @since 1.0.2
* @see MockHttpServletRequest
*/
public class DelegatingServletInputStream extends ServletInputStream {
private final InputStream sourceStream;
/**
* Create a DelegatingServletInputStream for the given source stream.
* @param sourceStream the source stream (never <code>null</code>)
*/
public DelegatingServletInputStream(InputStream sourceStream) {
Assert.notNull(sourceStream, "Source InputStream must not be null");
this.sourceStream = sourceStream;
}
/**
* Return the underlying source stream (never <code>null</code>).
*/
public final InputStream getSourceStream() {
return this.sourceStream;
}
public int read() throws IOException {
return this.sourceStream.read();
}
public void close() throws IOException {
super.close();
this.sourceStream.close();
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletInputStream;
import org.springframework.util.Assert;
/**
* Delegating implementation of {@link javax.servlet.ServletInputStream}.
*
* <p>Used by {@link MockHttpServletRequest}; typically not directly
* used for testing application controllers.
*
* @author Juergen Hoeller
* @since 1.0.2
* @see MockHttpServletRequest
*/
public class DelegatingServletInputStream extends ServletInputStream {
private final InputStream sourceStream;
/**
* Create a DelegatingServletInputStream for the given source stream.
* @param sourceStream the source stream (never <code>null</code>)
*/
public DelegatingServletInputStream(InputStream sourceStream) {
Assert.notNull(sourceStream, "Source InputStream must not be null");
this.sourceStream = sourceStream;
}
/**
* Return the underlying source stream (never <code>null</code>).
*/
public final InputStream getSourceStream() {
return this.sourceStream;
}
public int read() throws IOException {
return this.sourceStream.read();
}
public void close() throws IOException {
super.close();
this.sourceStream.close();
}
}

View File

@@ -1,71 +1,71 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import org.springframework.util.Assert;
/**
* Delegating implementation of {@link javax.servlet.ServletOutputStream}.
*
* <p>Used by {@link MockHttpServletResponse}; typically not directly
* used for testing application controllers.
*
* @author Juergen Hoeller
* @since 1.0.2
* @see MockHttpServletResponse
*/
public class DelegatingServletOutputStream extends ServletOutputStream {
private final OutputStream targetStream;
/**
* Create a DelegatingServletOutputStream for the given target stream.
* @param targetStream the target stream (never <code>null</code>)
*/
public DelegatingServletOutputStream(OutputStream targetStream) {
Assert.notNull(targetStream, "Target OutputStream must not be null");
this.targetStream = targetStream;
}
/**
* Return the underlying target stream (never <code>null</code>).
*/
public final OutputStream getTargetStream() {
return this.targetStream;
}
public void write(int b) throws IOException {
this.targetStream.write(b);
}
public void flush() throws IOException {
super.flush();
this.targetStream.flush();
}
public void close() throws IOException {
super.close();
this.targetStream.close();
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletOutputStream;
import org.springframework.util.Assert;
/**
* Delegating implementation of {@link javax.servlet.ServletOutputStream}.
*
* <p>Used by {@link MockHttpServletResponse}; typically not directly
* used for testing application controllers.
*
* @author Juergen Hoeller
* @since 1.0.2
* @see MockHttpServletResponse
*/
public class DelegatingServletOutputStream extends ServletOutputStream {
private final OutputStream targetStream;
/**
* Create a DelegatingServletOutputStream for the given target stream.
* @param targetStream the target stream (never <code>null</code>)
*/
public DelegatingServletOutputStream(OutputStream targetStream) {
Assert.notNull(targetStream, "Target OutputStream must not be null");
this.targetStream = targetStream;
}
/**
* Return the underlying target stream (never <code>null</code>).
*/
public final OutputStream getTargetStream() {
return this.targetStream;
}
public void write(int b) throws IOException {
this.targetStream.write(b);
}
public void flush() throws IOException {
super.flush();
this.targetStream.flush();
}
public void close() throws IOException {
super.close();
this.targetStream.close();
}
}

View File

@@ -1,96 +1,96 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Internal helper class that serves as value holder for request headers.
*
* @author Juergen Hoeller
* @author Rick Evans
* @since 2.0.1
*/
class HeaderValueHolder {
private final List<Object> values = new LinkedList<Object>();
public void setValue(Object value) {
this.values.clear();
this.values.add(value);
}
public void addValue(Object value) {
this.values.add(value);
}
public void addValues(Collection<?> values) {
this.values.addAll(values);
}
public void addValueArray(Object values) {
CollectionUtils.mergeArrayIntoCollection(values, this.values);
}
public List<Object> getValues() {
return Collections.unmodifiableList(this.values);
}
public List<String> getStringValues() {
List<String> stringList = new ArrayList<String>(this.values.size());
for (Object value : this.values) {
stringList.add(value.toString());
}
return Collections.unmodifiableList(stringList);
}
public Object getValue() {
return (!this.values.isEmpty() ? this.values.get(0) : null);
}
public String getStringValue() {
return (!this.values.isEmpty() ? this.values.get(0).toString() : null);
}
/**
* Find a HeaderValueHolder by name, ignoring casing.
* @param headers the Map of header names to HeaderValueHolders
* @param name the name of the desired header
* @return the corresponding HeaderValueHolder,
* or <code>null</code> if none found
*/
public static HeaderValueHolder getByName(Map<String, HeaderValueHolder> headers, String name) {
Assert.notNull(name, "Header name must not be null");
for (String headerName : headers.keySet()) {
if (headerName.equalsIgnoreCase(name)) {
return headers.get(headerName);
}
}
return null;
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
/**
* Internal helper class that serves as value holder for request headers.
*
* @author Juergen Hoeller
* @author Rick Evans
* @since 2.0.1
*/
class HeaderValueHolder {
private final List<Object> values = new LinkedList<Object>();
public void setValue(Object value) {
this.values.clear();
this.values.add(value);
}
public void addValue(Object value) {
this.values.add(value);
}
public void addValues(Collection<?> values) {
this.values.addAll(values);
}
public void addValueArray(Object values) {
CollectionUtils.mergeArrayIntoCollection(values, this.values);
}
public List<Object> getValues() {
return Collections.unmodifiableList(this.values);
}
public List<String> getStringValues() {
List<String> stringList = new ArrayList<String>(this.values.size());
for (Object value : this.values) {
stringList.add(value.toString());
}
return Collections.unmodifiableList(stringList);
}
public Object getValue() {
return (!this.values.isEmpty() ? this.values.get(0) : null);
}
public String getStringValue() {
return (!this.values.isEmpty() ? this.values.get(0).toString() : null);
}
/**
* Find a HeaderValueHolder by name, ignoring casing.
* @param headers the Map of header names to HeaderValueHolders
* @param name the name of the desired header
* @return the corresponding HeaderValueHolder,
* or <code>null</code> if none found
*/
public static HeaderValueHolder getByName(Map<String, HeaderValueHolder> headers, String name) {
Assert.notNull(name, "Header name must not be null");
for (String headerName : headers.keySet()) {
if (headerName.equalsIgnoreCase(name)) {
return headers.get(headerName);
}
}
return null;
}
}

View File

@@ -1,246 +1,246 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.servlet.http.HttpSession} interface.
* Supports the Servlet 2.4 API level.
*
* <p>Used for testing the web framework; also useful for testing
* application controllers.
*
* @author Juergen Hoeller
* @author Rod Johnson
* @author Mark Fisher
* @since 1.0.2
*/
public class MockHttpSession implements HttpSession {
public static final String SESSION_COOKIE_NAME = "JSESSION";
private static int nextId = 1;
private final String id;
private final long creationTime = System.currentTimeMillis();
private int maxInactiveInterval;
private long lastAccessedTime = System.currentTimeMillis();
private final ServletContext servletContext;
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private boolean invalid = false;
private boolean isNew = true;
/**
* Create a new MockHttpSession with a default {@link MockServletContext}.
* @see MockServletContext
*/
public MockHttpSession() {
this(null);
}
/**
* Create a new MockHttpSession.
* @param servletContext the ServletContext that the session runs in
*/
public MockHttpSession(ServletContext servletContext) {
this(servletContext, null);
}
/**
* Create a new MockHttpSession.
* @param servletContext the ServletContext that the session runs in
* @param id a unique identifier for this session
*/
public MockHttpSession(ServletContext servletContext, String id) {
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
this.id = (id != null ? id : Integer.toString(nextId++));
}
public long getCreationTime() {
return this.creationTime;
}
public String getId() {
return this.id;
}
public void access() {
this.lastAccessedTime = System.currentTimeMillis();
this.isNew = false;
}
public long getLastAccessedTime() {
return this.lastAccessedTime;
}
public ServletContext getServletContext() {
return this.servletContext;
}
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
public int getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
public HttpSessionContext getSessionContext() {
throw new UnsupportedOperationException("getSessionContext");
}
public Object getAttribute(String name) {
Assert.notNull(name, "Attribute name must not be null");
return this.attributes.get(name);
}
public Object getValue(String name) {
return getAttribute(name);
}
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public String[] getValueNames() {
return this.attributes.keySet().toArray(new String[this.attributes.size()]);
}
public void setAttribute(String name, Object value) {
Assert.notNull(name, "Attribute name must not be null");
if (value != null) {
this.attributes.put(name, value);
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
}
}
else {
removeAttribute(name);
}
}
public void putValue(String name, Object value) {
setAttribute(name, value);
}
public void removeAttribute(String name) {
Assert.notNull(name, "Attribute name must not be null");
Object value = this.attributes.remove(name);
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
}
}
public void removeValue(String name) {
removeAttribute(name);
}
/**
* Clear all of this session's attributes.
*/
public void clearAttributes() {
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
String name = entry.getKey();
Object value = entry.getValue();
it.remove();
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
}
}
}
public void invalidate() {
this.invalid = true;
clearAttributes();
}
public boolean isInvalid() {
return this.invalid;
}
public void setNew(boolean value) {
this.isNew = value;
}
public boolean isNew() {
return this.isNew;
}
/**
* Serialize the attributes of this session into an object that can
* be turned into a byte array with standard Java serialization.
* @return a representation of this session's serialized state
*/
public Serializable serializeState() {
HashMap<String, Serializable> state = new HashMap<String, Serializable>();
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
String name = entry.getKey();
Object value = entry.getValue();
it.remove();
if (value instanceof Serializable) {
state.put(name, (Serializable) value);
}
else {
// Not serializable... Servlet containers usually automatically
// unbind the attribute in this case.
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
}
}
}
return state;
}
/**
* Deserialize the attributes of this session from a state object
* created by {@link #serializeState()}.
* @param state a representation of this session's serialized state
*/
@SuppressWarnings("unchecked")
public void deserializeState(Serializable state) {
Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");
this.attributes.putAll((Map<String, Object>) state);
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import java.io.Serializable;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
import javax.servlet.http.HttpSessionContext;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.servlet.http.HttpSession} interface.
* Supports the Servlet 2.4 API level.
*
* <p>Used for testing the web framework; also useful for testing
* application controllers.
*
* @author Juergen Hoeller
* @author Rod Johnson
* @author Mark Fisher
* @since 1.0.2
*/
public class MockHttpSession implements HttpSession {
public static final String SESSION_COOKIE_NAME = "JSESSION";
private static int nextId = 1;
private final String id;
private final long creationTime = System.currentTimeMillis();
private int maxInactiveInterval;
private long lastAccessedTime = System.currentTimeMillis();
private final ServletContext servletContext;
private final Map<String, Object> attributes = new LinkedHashMap<String, Object>();
private boolean invalid = false;
private boolean isNew = true;
/**
* Create a new MockHttpSession with a default {@link MockServletContext}.
* @see MockServletContext
*/
public MockHttpSession() {
this(null);
}
/**
* Create a new MockHttpSession.
* @param servletContext the ServletContext that the session runs in
*/
public MockHttpSession(ServletContext servletContext) {
this(servletContext, null);
}
/**
* Create a new MockHttpSession.
* @param servletContext the ServletContext that the session runs in
* @param id a unique identifier for this session
*/
public MockHttpSession(ServletContext servletContext, String id) {
this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
this.id = (id != null ? id : Integer.toString(nextId++));
}
public long getCreationTime() {
return this.creationTime;
}
public String getId() {
return this.id;
}
public void access() {
this.lastAccessedTime = System.currentTimeMillis();
this.isNew = false;
}
public long getLastAccessedTime() {
return this.lastAccessedTime;
}
public ServletContext getServletContext() {
return this.servletContext;
}
public void setMaxInactiveInterval(int interval) {
this.maxInactiveInterval = interval;
}
public int getMaxInactiveInterval() {
return this.maxInactiveInterval;
}
public HttpSessionContext getSessionContext() {
throw new UnsupportedOperationException("getSessionContext");
}
public Object getAttribute(String name) {
Assert.notNull(name, "Attribute name must not be null");
return this.attributes.get(name);
}
public Object getValue(String name) {
return getAttribute(name);
}
public Enumeration<String> getAttributeNames() {
return Collections.enumeration(this.attributes.keySet());
}
public String[] getValueNames() {
return this.attributes.keySet().toArray(new String[this.attributes.size()]);
}
public void setAttribute(String name, Object value) {
Assert.notNull(name, "Attribute name must not be null");
if (value != null) {
this.attributes.put(name, value);
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueBound(new HttpSessionBindingEvent(this, name, value));
}
}
else {
removeAttribute(name);
}
}
public void putValue(String name, Object value) {
setAttribute(name, value);
}
public void removeAttribute(String name) {
Assert.notNull(name, "Attribute name must not be null");
Object value = this.attributes.remove(name);
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
}
}
public void removeValue(String name) {
removeAttribute(name);
}
/**
* Clear all of this session's attributes.
*/
public void clearAttributes() {
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
String name = entry.getKey();
Object value = entry.getValue();
it.remove();
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
}
}
}
public void invalidate() {
this.invalid = true;
clearAttributes();
}
public boolean isInvalid() {
return this.invalid;
}
public void setNew(boolean value) {
this.isNew = value;
}
public boolean isNew() {
return this.isNew;
}
/**
* Serialize the attributes of this session into an object that can
* be turned into a byte array with standard Java serialization.
* @return a representation of this session's serialized state
*/
public Serializable serializeState() {
HashMap<String, Serializable> state = new HashMap<String, Serializable>();
for (Iterator<Map.Entry<String, Object>> it = this.attributes.entrySet().iterator(); it.hasNext();) {
Map.Entry<String, Object> entry = it.next();
String name = entry.getKey();
Object value = entry.getValue();
it.remove();
if (value instanceof Serializable) {
state.put(name, (Serializable) value);
}
else {
// Not serializable... Servlet containers usually automatically
// unbind the attribute in this case.
if (value instanceof HttpSessionBindingListener) {
((HttpSessionBindingListener) value).valueUnbound(new HttpSessionBindingEvent(this, name, value));
}
}
}
return state;
}
/**
* Deserialize the attributes of this session from a state object
* created by {@link #serializeState()}.
* @param state a representation of this session's serialized state
*/
@SuppressWarnings("unchecked")
public void deserializeState(Serializable state) {
Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");
this.attributes.putAll((Map<String, Object>) state);
}
}

View File

@@ -1,91 +1,91 @@
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.servlet.RequestDispatcher} interface.
*
* <p>Used for testing the web framework; typically not necessary for
* testing application controllers.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 1.0.2
*/
public class MockRequestDispatcher implements RequestDispatcher {
private final Log logger = LogFactory.getLog(getClass());
private final String url;
/**
* Create a new MockRequestDispatcher for the given URL.
* @param url the URL to dispatch to.
*/
public MockRequestDispatcher(String url) {
Assert.notNull(url, "URL must not be null");
this.url = url;
}
public void forward(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
if (response.isCommitted()) {
throw new IllegalStateException("Cannot perform forward - response is already committed");
}
getMockHttpServletResponse(response).setForwardedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
}
}
public void include(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
getMockHttpServletResponse(response).addIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
}
}
/**
* Obtain the underlying MockHttpServletResponse,
* unwrapping {@link HttpServletResponseWrapper} decorators if necessary.
*/
protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) {
if (response instanceof MockHttpServletResponse) {
return (MockHttpServletResponse) response;
}
if (response instanceof HttpServletResponseWrapper) {
return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse());
}
throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse");
}
}
/*
* Copyright 2002-2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.mock.web;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
/**
* Mock implementation of the {@link javax.servlet.RequestDispatcher} interface.
*
* <p>Used for testing the web framework; typically not necessary for
* testing application controllers.
*
* @author Rod Johnson
* @author Juergen Hoeller
* @since 1.0.2
*/
public class MockRequestDispatcher implements RequestDispatcher {
private final Log logger = LogFactory.getLog(getClass());
private final String url;
/**
* Create a new MockRequestDispatcher for the given URL.
* @param url the URL to dispatch to.
*/
public MockRequestDispatcher(String url) {
Assert.notNull(url, "URL must not be null");
this.url = url;
}
public void forward(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
if (response.isCommitted()) {
throw new IllegalStateException("Cannot perform forward - response is already committed");
}
getMockHttpServletResponse(response).setForwardedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: forwarding to URL [" + this.url + "]");
}
}
public void include(ServletRequest request, ServletResponse response) {
Assert.notNull(request, "Request must not be null");
Assert.notNull(response, "Response must not be null");
getMockHttpServletResponse(response).addIncludedUrl(this.url);
if (logger.isDebugEnabled()) {
logger.debug("MockRequestDispatcher: including URL [" + this.url + "]");
}
}
/**
* Obtain the underlying MockHttpServletResponse,
* unwrapping {@link HttpServletResponseWrapper} decorators if necessary.
*/
protected MockHttpServletResponse getMockHttpServletResponse(ServletResponse response) {
if (response instanceof MockHttpServletResponse) {
return (MockHttpServletResponse) response;
}
if (response instanceof HttpServletResponseWrapper) {
return getMockHttpServletResponse(((HttpServletResponseWrapper) response).getResponse());
}
throw new IllegalArgumentException("MockRequestDispatcher requires MockHttpServletResponse");
}
}

View File

@@ -1,100 +1,100 @@
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.request;
import javax.servlet.ServletContextEvent;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextCleanupListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
/**
* @author Juergen Hoeller
*/
public class WebApplicationContextScopeTests {
private static final String NAME = "scoped";
private WebApplicationContext initApplicationContext(String scope) {
MockServletContext sc = new MockServletContext();
GenericWebApplicationContext ac = new GenericWebApplicationContext(sc);
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(DerivedTestBean.class);
bd.setScope(scope);
ac.registerBeanDefinition(NAME, bd);
ac.refresh();
return ac;
}
@Test
public void testRequestScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_REQUEST);
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
requestAttributes.requestCompleted();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testSessionScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_SESSION);
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getSession().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getSession().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
request.getSession().invalidate();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testApplicationScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION);
assertNull(ac.getServletContext().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, ac.getServletContext().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext()));
assertTrue(bean.wasDestroyed());
}
}
/*
* Copyright 2002-2009 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.request;
import javax.servlet.ServletContextEvent;
import static org.junit.Assert.*;
import org.junit.Test;
import org.springframework.beans.DerivedTestBean;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.ContextCleanupListener;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.GenericWebApplicationContext;
/**
* @author Juergen Hoeller
*/
public class WebApplicationContextScopeTests {
private static final String NAME = "scoped";
private WebApplicationContext initApplicationContext(String scope) {
MockServletContext sc = new MockServletContext();
GenericWebApplicationContext ac = new GenericWebApplicationContext(sc);
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setBeanClass(DerivedTestBean.class);
bd.setScope(scope);
ac.registerBeanDefinition(NAME, bd);
ac.refresh();
return ac;
}
@Test
public void testRequestScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_REQUEST);
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
requestAttributes.requestCompleted();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testSessionScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_SESSION);
MockHttpServletRequest request = new MockHttpServletRequest();
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
RequestContextHolder.setRequestAttributes(requestAttributes);
try {
assertNull(request.getSession().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, request.getSession().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
request.getSession().invalidate();
assertTrue(bean.wasDestroyed());
}
finally {
RequestContextHolder.setRequestAttributes(null);
}
}
@Test
public void testApplicationScope() {
WebApplicationContext ac = initApplicationContext(WebApplicationContext.SCOPE_APPLICATION);
assertNull(ac.getServletContext().getAttribute(NAME));
DerivedTestBean bean = ac.getBean(NAME, DerivedTestBean.class);
assertSame(bean, ac.getServletContext().getAttribute(NAME));
assertSame(bean, ac.getBean(NAME));
new ContextCleanupListener().contextDestroyed(new ServletContextEvent(ac.getServletContext()));
assertTrue(bean.wasDestroyed());
}
}

View File

@@ -1,62 +1,62 @@
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.support;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class SpringBeanAutowiringSupportTests {
@Test
public void testProcessInjectionBasedOnServletContext() {
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "tb");
wac.registerSingleton("testBean", TestBean.class, pvs);
wac.setServletContext(sc);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
InjectionTarget target = new InjectionTarget();
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
assertTrue(target.testBean instanceof TestBean);
assertEquals("tb", target.name);
}
public static class InjectionTarget {
@Autowired
public ITestBean testBean;
@Value("#{testBean.name}")
public String name;
}
}
/*
* Copyright 2002-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.web.context.support;
import org.junit.Test;
import org.springframework.beans.ITestBean;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.TestBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.context.WebApplicationContext;
import static org.junit.Assert.*;
/**
* @author Juergen Hoeller
*/
public class SpringBeanAutowiringSupportTests {
@Test
public void testProcessInjectionBasedOnServletContext() {
MockServletContext sc = new MockServletContext();
StaticWebApplicationContext wac = new StaticWebApplicationContext();
MutablePropertyValues pvs = new MutablePropertyValues();
pvs.add("name", "tb");
wac.registerSingleton("testBean", TestBean.class, pvs);
wac.setServletContext(sc);
wac.refresh();
sc.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
InjectionTarget target = new InjectionTarget();
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(target, sc);
assertTrue(target.testBean instanceof TestBean);
assertEquals("tb", target.name);
}
public static class InjectionTarget {
@Autowired
public ITestBean testBean;
@Value("#{testBean.name}")
public String name;
}
}