首页

关于spring-test源码包中对JSP定义页面对象接口(PageContext/HttpSession/HttpServletRequest等)基于测试mock场景进行重写源码示例

标签:spring-test,springframework,mock,jsp页面对象,HttpServletRequest实现,HttpServletResponse实现,HttpSession实现,JspWriter实现,ServletContext实现     发布时间:2018-09-11   

一、前言

关于spring-test源码包中org.springframework.mock.web.MockServletContext、org.springframework.mock.web.MockServletConfig、org.springframework.mock.web.RequestDispatcher、org.springframework.mock.web.MockPageContext、org.springframework.mock.web.MockJspWriter、org.springframework.mock.web.MockHttpSession、org.springframework.mock.web.MockHttpServletResponse、org.springframework.mock.web.MockHttpServletRequest、org.springframework.mock.web.MockFilterConfig、org.springframework.mock.web.MockFilterChain实现类,对javax.servlet定义ServletConfig、RequestDispatcher、PageContext、JspWriter、HttpSession、HttpServletResponse、HttpServletRequest接口页面对象进行实现,详情参见源码说明部分。

二、源码说明

1. MockServletContext、MockServletConfig、MockFilterConfig、MockFilterChain类

package org.springframework.mock.web;@b@@b@import java.io.File;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.net.MalformedURLException;@b@import java.net.URL;@b@import java.util.Collections;@b@import java.util.Enumeration;@b@import java.util.EventListener;@b@import java.util.HashMap;@b@import java.util.LinkedHashMap;@b@import java.util.LinkedHashSet;@b@import java.util.Map;@b@import java.util.Set;@b@import javax.activation.FileTypeMap;@b@import javax.servlet.Filter;@b@import javax.servlet.FilterRegistration;@b@import javax.servlet.FilterRegistration.Dynamic;@b@import javax.servlet.RequestDispatcher;@b@import javax.servlet.Servlet;@b@import javax.servlet.ServletException;@b@import javax.servlet.ServletRegistration;@b@import javax.servlet.ServletRegistration.Dynamic;@b@import javax.servlet.SessionCookieConfig;@b@import javax.servlet.SessionTrackingMode;@b@import javax.servlet.descriptor.JspConfigDescriptor;@b@import org.apache.commons.logging.Log;@b@import org.apache.commons.logging.LogFactory;@b@import org.springframework.core.io.DefaultResourceLoader;@b@import org.springframework.core.io.Resource;@b@import org.springframework.core.io.ResourceLoader;@b@import org.springframework.util.Assert;@b@import org.springframework.util.ClassUtils;@b@import org.springframework.util.ObjectUtils;@b@@b@public class MockServletContext@b@  implements javax.servlet.ServletContext@b@{@b@  private static final String COMMON_DEFAULT_SERVLET_NAME = "default";@b@  private static final String TEMP_DIR_SYSTEM_PROPERTY = "java.io.tmpdir";@b@  private static final Set<SessionTrackingMode> DEFAULT_SESSION_TRACKING_MODES = new LinkedHashSet(3);@b@  private final Log logger;@b@  private final ResourceLoader resourceLoader;@b@  private final String resourceBasePath;@b@  private String contextPath;@b@  private final Map<String, javax.servlet.ServletContext> contexts;@b@  private int majorVersion;@b@  private int minorVersion;@b@  private int effectiveMajorVersion;@b@  private int effectiveMinorVersion;@b@  private final Map<String, RequestDispatcher> namedRequestDispatchers;@b@  private String defaultServletName;@b@  private final Map<String, String> initParameters;@b@  private final Map<String, Object> attributes;@b@  private String servletContextName;@b@  private final Set<String> declaredRoles;@b@  private Set<SessionTrackingMode> sessionTrackingModes;@b@  private final SessionCookieConfig sessionCookieConfig;@b@@b@  public MockServletContext()@b@  {@b@    this("", null);@b@  }@b@@b@  public MockServletContext(String resourceBasePath)@b@  {@b@    this(resourceBasePath, null);@b@  }@b@@b@  public MockServletContext(ResourceLoader resourceLoader)@b@  {@b@    this("", resourceLoader);@b@  }@b@@b@  public MockServletContext(String resourceBasePath, ResourceLoader resourceLoader)@b@  {@b@    this.logger = LogFactory.getLog(super.getClass());@b@@b@    this.contextPath = "";@b@@b@    this.contexts = new HashMap();@b@@b@    this.majorVersion = 3;@b@@b@    this.minorVersion = 0;@b@@b@    this.effectiveMajorVersion = 3;@b@@b@    this.effectiveMinorVersion = 0;@b@@b@    this.namedRequestDispatchers = new HashMap();@b@@b@    this.defaultServletName = "default";@b@@b@    this.initParameters = new LinkedHashMap();@b@@b@    this.attributes = new LinkedHashMap();@b@@b@    this.servletContextName = "MockServletContext";@b@@b@    this.declaredRoles = new LinkedHashSet();@b@@b@    this.sessionCookieConfig = new MockSessionCookieConfig();@b@@b@    this.resourceLoader = new DefaultResourceLoader();@b@    this.resourceBasePath = ((resourceBasePath != null) ? resourceBasePath : "");@b@@b@    String tempDir = System.getProperty("java.io.tmpdir");@b@    if (tempDir != null) {@b@      this.attributes.put("javax.servlet.context.tempdir", new File(tempDir));@b@    }@b@@b@    registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));@b@  }@b@@b@  protected String getResourceLocation(String path)@b@  {@b@    if (!(path.startsWith("/")))@b@      path = "/" + path;@b@@b@    return this.resourceBasePath + path;@b@  }@b@@b@  public void setContextPath(String contextPath) {@b@    this.contextPath = ((contextPath != null) ? contextPath : "");@b@  }@b@@b@  public String getContextPath()@b@  {@b@    return this.contextPath;@b@  }@b@@b@  public void registerContext(String contextPath, javax.servlet.ServletContext context) {@b@    this.contexts.put(contextPath, context);@b@  }@b@@b@  public javax.servlet.ServletContext getContext(String contextPath)@b@  {@b@    if (this.contextPath.equals(contextPath))@b@      return this;@b@@b@    return ((javax.servlet.ServletContext)this.contexts.get(contextPath));@b@  }@b@@b@  public void setMajorVersion(int majorVersion) {@b@    this.majorVersion = majorVersion;@b@  }@b@@b@  public int getMajorVersion()@b@  {@b@    return this.majorVersion;@b@  }@b@@b@  public void setMinorVersion(int minorVersion) {@b@    this.minorVersion = minorVersion;@b@  }@b@@b@  public int getMinorVersion()@b@  {@b@    return this.minorVersion;@b@  }@b@@b@  public void setEffectiveMajorVersion(int effectiveMajorVersion) {@b@    this.effectiveMajorVersion = effectiveMajorVersion;@b@  }@b@@b@  public int getEffectiveMajorVersion()@b@  {@b@    return this.effectiveMajorVersion;@b@  }@b@@b@  public void setEffectiveMinorVersion(int effectiveMinorVersion) {@b@    this.effectiveMinorVersion = effectiveMinorVersion;@b@  }@b@@b@  public int getEffectiveMinorVersion()@b@  {@b@    return this.effectiveMinorVersion;@b@  }@b@@b@  public String getMimeType(String filePath)@b@  {@b@    String mimeType = FileTypeMap.getDefaultFileTypeMap().getContentType(filePath);@b@    return (("application/octet-stream".equals(mimeType)) ? null : mimeType);@b@  }@b@@b@  public Set<String> getResourcePaths(String path)@b@  {@b@    String actualPath = path + "/";@b@    Resource resource = this.resourceLoader.getResource(getResourceLocation(actualPath));@b@    try {@b@      File file = resource.getFile();@b@      String[] fileList = file.list();@b@      if (ObjectUtils.isEmpty(fileList))@b@        return null;@b@@b@      Set resourcePaths = new LinkedHashSet(fileList.length);@b@      String[] arrayOfString1 = fileList; int i = arrayOfString1.length; for (int j = 0; j < i; ++j) { String fileEntry = arrayOfString1[j];@b@        String resultPath = actualPath + fileEntry;@b@        if (resource.createRelative(fileEntry).getFile().isDirectory())@b@          resultPath = resultPath + "/";@b@@b@        resourcePaths.add(resultPath);@b@      }@b@      return resourcePaths;@b@    }@b@    catch (IOException ex) {@b@      this.logger.warn("Couldn't get resource paths for " + resource, ex); }@b@    return null;@b@  }@b@@b@  public URL getResource(String path)@b@    throws MalformedURLException@b@  {@b@    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));@b@    if (!(resource.exists()))@b@      return null;@b@    try@b@    {@b@      return resource.getURL();@b@    }@b@    catch (MalformedURLException ex) {@b@      throw ex;@b@    }@b@    catch (IOException ex) {@b@      this.logger.warn("Couldn't get URL for " + resource, ex); }@b@    return null;@b@  }@b@@b@  public InputStream getResourceAsStream(String path)@b@  {@b@    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));@b@    if (!(resource.exists()))@b@      return null;@b@    try@b@    {@b@      return resource.getInputStream();@b@    }@b@    catch (IOException ex) {@b@      this.logger.warn("Couldn't open InputStream for " + resource, ex); }@b@    return null;@b@  }@b@@b@  public RequestDispatcher getRequestDispatcher(String path)@b@  {@b@    if (!(path.startsWith("/")))@b@      throw new IllegalArgumentException("RequestDispatcher path at ServletContext level must start with '/'");@b@@b@    return new MockRequestDispatcher(path);@b@  }@b@@b@  public RequestDispatcher getNamedDispatcher(String path)@b@  {@b@    return ((RequestDispatcher)this.namedRequestDispatchers.get(path));@b@  }@b@@b@  public void registerNamedDispatcher(String name, RequestDispatcher requestDispatcher)@b@  {@b@    Assert.notNull(name, "RequestDispatcher name must not be null");@b@    Assert.notNull(requestDispatcher, "RequestDispatcher must not be null");@b@    this.namedRequestDispatchers.put(name, requestDispatcher);@b@  }@b@@b@  public void unregisterNamedDispatcher(String name)@b@  {@b@    Assert.notNull(name, "RequestDispatcher name must not be null");@b@    this.namedRequestDispatchers.remove(name);@b@  }@b@@b@  public String getDefaultServletName()@b@  {@b@    return this.defaultServletName;@b@  }@b@@b@  public void setDefaultServletName(String defaultServletName)@b@  {@b@    Assert.hasText(defaultServletName, "defaultServletName must not be null or empty");@b@    unregisterNamedDispatcher(this.defaultServletName);@b@    this.defaultServletName = defaultServletName;@b@    registerNamedDispatcher(this.defaultServletName, new MockRequestDispatcher(this.defaultServletName));@b@  }@b@@b@  @Deprecated@b@  public Servlet getServlet(String name)@b@  {@b@    return null;@b@  }@b@@b@  @Deprecated@b@  public Enumeration<Servlet> getServlets()@b@  {@b@    return Collections.enumeration(Collections.emptySet());@b@  }@b@@b@  @Deprecated@b@  public Enumeration<String> getServletNames()@b@  {@b@    return Collections.enumeration(Collections.emptySet());@b@  }@b@@b@  public void log(String message)@b@  {@b@    this.logger.info(message);@b@  }@b@@b@  @Deprecated@b@  public void log(Exception ex, String message)@b@  {@b@    this.logger.info(message, ex);@b@  }@b@@b@  public void log(String message, Throwable ex)@b@  {@b@    this.logger.info(message, ex);@b@  }@b@@b@  public String getRealPath(String path)@b@  {@b@    Resource resource = this.resourceLoader.getResource(getResourceLocation(path));@b@    try {@b@      return resource.getFile().getAbsolutePath();@b@    }@b@    catch (IOException ex) {@b@      this.logger.warn("Couldn't determine real path of resource " + resource, ex); }@b@    return null;@b@  }@b@@b@  public String getServerInfo()@b@  {@b@    return "MockServletContext";@b@  }@b@@b@  public String getInitParameter(String name)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    return ((String)this.initParameters.get(name));@b@  }@b@@b@  public Enumeration<String> getInitParameterNames()@b@  {@b@    return Collections.enumeration(this.initParameters.keySet());@b@  }@b@@b@  public boolean setInitParameter(String name, String value)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    if (this.initParameters.containsKey(name))@b@      return false;@b@@b@    this.initParameters.put(name, value);@b@    return true;@b@  }@b@@b@  public void addInitParameter(String name, String value) {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    this.initParameters.put(name, value);@b@  }@b@@b@  public Object getAttribute(String name)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    return this.attributes.get(name);@b@  }@b@@b@  public Enumeration<String> getAttributeNames()@b@  {@b@    return Collections.enumeration(new LinkedHashSet(this.attributes.keySet()));@b@  }@b@@b@  public void setAttribute(String name, Object value)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    if (value != null) {@b@      this.attributes.put(name, value);@b@    }@b@    else@b@      this.attributes.remove(name);@b@  }@b@@b@  public void removeAttribute(String name)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    this.attributes.remove(name);@b@  }@b@@b@  public void setServletContextName(String servletContextName) {@b@    this.servletContextName = servletContextName;@b@  }@b@@b@  public String getServletContextName()@b@  {@b@    return this.servletContextName;@b@  }@b@@b@  public ClassLoader getClassLoader()@b@  {@b@    return ClassUtils.getDefaultClassLoader();@b@  }@b@@b@  public void declareRoles(String[] roleNames)@b@  {@b@    Assert.notNull(roleNames, "Role names array must not be null");@b@    String[] arrayOfString = roleNames; int i = arrayOfString.length; for (int j = 0; j < i; ++j) { String roleName = arrayOfString[j];@b@      Assert.hasLength(roleName, "Role name must not be empty");@b@      this.declaredRoles.add(roleName);@b@    }@b@  }@b@@b@  public Set<String> getDeclaredRoles() {@b@    return Collections.unmodifiableSet(this.declaredRoles);@b@  }@b@@b@  public void setSessionTrackingModes(Set<SessionTrackingMode> sessionTrackingModes)@b@    throws IllegalStateException, IllegalArgumentException@b@  {@b@    this.sessionTrackingModes = sessionTrackingModes;@b@  }@b@@b@  public Set<SessionTrackingMode> getDefaultSessionTrackingModes()@b@  {@b@    return DEFAULT_SESSION_TRACKING_MODES;@b@  }@b@@b@  public Set<SessionTrackingMode> getEffectiveSessionTrackingModes()@b@  {@b@    return ((this.sessionTrackingModes != null) ? @b@      Collections.unmodifiableSet(this.sessionTrackingModes)@b@       : DEFAULT_SESSION_TRACKING_MODES);@b@  }@b@@b@  public SessionCookieConfig getSessionCookieConfig()@b@  {@b@    return this.sessionCookieConfig;@b@  }@b@@b@  public JspConfigDescriptor getJspConfigDescriptor()@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public ServletRegistration.Dynamic addServlet(String servletName, String className)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public ServletRegistration.Dynamic addServlet(String servletName, Class<? extends Servlet> servletClass)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public <T extends Servlet> T createServlet(Class<T> c) throws ServletException@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public ServletRegistration getServletRegistration(String servletName)@b@  {@b@    return null;@b@  }@b@@b@  public Map<String, ? extends ServletRegistration> getServletRegistrations()@b@  {@b@    return Collections.emptyMap();@b@  }@b@@b@  public FilterRegistration.Dynamic addFilter(String filterName, String className)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public FilterRegistration.Dynamic addFilter(String filterName, Filter filter)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public <T extends Filter> T createFilter(Class<T> c) throws ServletException@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public FilterRegistration getFilterRegistration(String filterName)@b@  {@b@    return null;@b@  }@b@@b@  public Map<String, ? extends FilterRegistration> getFilterRegistrations()@b@  {@b@    return Collections.emptyMap();@b@  }@b@@b@  public void addListener(Class<? extends EventListener> listenerClass)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public void addListener(String className)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public <T extends EventListener> void addListener(T t)@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public <T extends EventListener> T createListener(Class<T> c) throws ServletException@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  static@b@  {@b@    DEFAULT_SESSION_TRACKING_MODES.add(SessionTrackingMode.COOKIE);@b@    DEFAULT_SESSION_TRACKING_MODES.add(SessionTrackingMode.URL);@b@    DEFAULT_SESSION_TRACKING_MODES.add(SessionTrackingMode.SSL);@b@  }@b@}
package org.springframework.mock.web;@b@@b@import java.util.Collections;@b@import java.util.Enumeration;@b@import java.util.LinkedHashMap;@b@import java.util.Map;@b@import javax.servlet.ServletConfig;@b@import javax.servlet.ServletContext;@b@import org.springframework.util.Assert;@b@@b@public class MockServletConfig@b@  implements ServletConfig@b@{@b@  private final ServletContext servletContext;@b@  private final String servletName;@b@  private final Map<String, String> initParameters;@b@@b@  public MockServletConfig()@b@  {@b@    this(null, "");@b@  }@b@@b@  public MockServletConfig(String servletName)@b@  {@b@    this(null, servletName);@b@  }@b@@b@  public MockServletConfig(ServletContext servletContext)@b@  {@b@    this(servletContext, "");@b@  }@b@@b@  public MockServletConfig(ServletContext servletContext, String servletName)@b@  {@b@    this.initParameters = new LinkedHashMap();@b@@b@    this.servletContext = new MockServletContext();@b@    this.servletName = servletName;@b@  }@b@@b@  public String getServletName()@b@  {@b@    return this.servletName;@b@  }@b@@b@  public ServletContext getServletContext()@b@  {@b@    return this.servletContext;@b@  }@b@@b@  public void addInitParameter(String name, String value) {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    this.initParameters.put(name, value);@b@  }@b@@b@  public String getInitParameter(String name)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    return ((String)this.initParameters.get(name));@b@  }@b@@b@  public Enumeration<String> getInitParameterNames()@b@  {@b@    return Collections.enumeration(this.initParameters.keySet());@b@  }@b@}
package org.springframework.mock.web;@b@@b@import java.util.Collections;@b@import java.util.Enumeration;@b@import java.util.LinkedHashMap;@b@import java.util.Map;@b@import javax.servlet.FilterConfig;@b@import javax.servlet.ServletContext;@b@import org.springframework.util.Assert;@b@@b@public class MockFilterConfig@b@  implements FilterConfig@b@{@b@  private final ServletContext servletContext;@b@  private final String filterName;@b@  private final Map<String, String> initParameters;@b@@b@  public MockFilterConfig()@b@  {@b@    this(null, "");@b@  }@b@@b@  public MockFilterConfig(String filterName)@b@  {@b@    this(null, filterName);@b@  }@b@@b@  public MockFilterConfig(ServletContext servletContext)@b@  {@b@    this(servletContext, "");@b@  }@b@@b@  public MockFilterConfig(ServletContext servletContext, String filterName)@b@  {@b@    this.initParameters = new LinkedHashMap();@b@@b@    this.servletContext = new MockServletContext();@b@    this.filterName = filterName;@b@  }@b@@b@  public String getFilterName()@b@  {@b@    return this.filterName;@b@  }@b@@b@  public ServletContext getServletContext()@b@  {@b@    return this.servletContext;@b@  }@b@@b@  public void addInitParameter(String name, String value) {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    this.initParameters.put(name, value);@b@  }@b@@b@  public String getInitParameter(String name)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    return ((String)this.initParameters.get(name));@b@  }@b@@b@  public Enumeration<String> getInitParameterNames()@b@  {@b@    return Collections.enumeration(this.initParameters.keySet());@b@  }@b@}
package org.springframework.mock.web;@b@@b@import java.io.IOException;@b@import java.util.Arrays;@b@import java.util.Collections;@b@import java.util.Iterator;@b@import java.util.List;@b@import javax.servlet.Filter;@b@import javax.servlet.FilterChain;@b@import javax.servlet.FilterConfig;@b@import javax.servlet.Servlet;@b@import javax.servlet.ServletException;@b@import javax.servlet.ServletRequest;@b@import javax.servlet.ServletResponse;@b@import org.springframework.util.Assert;@b@import org.springframework.util.ObjectUtils;@b@@b@public class MockFilterChain@b@  implements FilterChain@b@{@b@  private ServletRequest request;@b@  private ServletResponse response;@b@  private final List<Filter> filters;@b@  private Iterator<Filter> iterator;@b@@b@  public MockFilterChain()@b@  {@b@    this.filters = Collections.emptyList();@b@  }@b@@b@  public MockFilterChain(Servlet servlet)@b@  {@b@    this.filters = initFilterList(servlet, new Filter[0]);@b@  }@b@@b@  public MockFilterChain(Servlet servlet, Filter[] filters)@b@  {@b@    Assert.notNull(filters, "filters cannot be null");@b@    Assert.noNullElements(filters, "filters cannot contain null values");@b@    this.filters = initFilterList(servlet, filters);@b@  }@b@@b@  private static List<Filter> initFilterList(Servlet servlet, Filter[] filters) {@b@    Filter[] allFilters = (Filter[])ObjectUtils.addObjectToArray(filters, new ServletFilterProxy(servlet, null));@b@    return Arrays.asList(allFilters);@b@  }@b@@b@  public ServletRequest getRequest()@b@  {@b@    return this.request;@b@  }@b@@b@  public ServletResponse getResponse()@b@  {@b@    return this.response;@b@  }@b@@b@  public void doFilter(ServletRequest request, ServletResponse response)@b@    throws IOException, ServletException@b@  {@b@    Assert.notNull(request, "Request must not be null");@b@    Assert.notNull(response, "Response must not be null");@b@    Assert.state(this.request == null, "This FilterChain has already been called!");@b@@b@    if (this.iterator == null) {@b@      this.iterator = this.filters.iterator();@b@    }@b@@b@    if (this.iterator.hasNext()) {@b@      Filter nextFilter = (Filter)this.iterator.next();@b@      nextFilter.doFilter(request, response, this);@b@    }@b@@b@    this.request = request;@b@    this.response = response;@b@  }@b@@b@  public void reset()@b@  {@b@    this.request = null;@b@    this.response = null;@b@    this.iterator = null;@b@  }@b@@b@  private static class ServletFilterProxy@b@    implements Filter@b@  {@b@    private final Servlet delegateServlet;@b@@b@    private ServletFilterProxy(Servlet servlet)@b@    {@b@      Assert.notNull(servlet, "servlet cannot be null");@b@      this.delegateServlet = servlet;@b@    }@b@@b@    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)@b@      throws IOException, ServletException@b@    {@b@      this.delegateServlet.service(request, response);@b@    }@b@@b@    public void init(FilterConfig filterConfig) throws ServletException@b@    {@b@    }@b@@b@    public void destroy()@b@    {@b@    }@b@@b@    public String toString()@b@    {@b@      return this.delegateServlet.toString();@b@    }@b@  }@b@}

2. HttpSession、HttpServletResponse、HttpServletRequest类

package org.springframework.mock.web;@b@@b@import java.io.Serializable;@b@import java.util.Collections;@b@import java.util.Enumeration;@b@import java.util.HashMap;@b@import java.util.Iterator;@b@import java.util.LinkedHashMap;@b@import java.util.LinkedHashSet;@b@import java.util.Map;@b@import java.util.Map.Entry;@b@import java.util.Set;@b@import javax.servlet.ServletContext;@b@import javax.servlet.http.HttpSession;@b@import javax.servlet.http.HttpSessionBindingEvent;@b@import javax.servlet.http.HttpSessionBindingListener;@b@import javax.servlet.http.HttpSessionContext;@b@import org.springframework.util.Assert;@b@@b@public class MockHttpSession@b@  implements HttpSession@b@{@b@  public static final String SESSION_COOKIE_NAME = "JSESSION";@b@  private static int nextId = 1;@b@  private String id;@b@  private final long creationTime;@b@  private int maxInactiveInterval;@b@  private long lastAccessedTime;@b@  private final ServletContext servletContext;@b@  private final Map<String, Object> attributes;@b@  private boolean invalid;@b@  private boolean isNew;@b@@b@  public MockHttpSession()@b@  {@b@    this(null);@b@  }@b@@b@  public MockHttpSession(ServletContext servletContext)@b@  {@b@    this(servletContext, null);@b@  }@b@@b@  public MockHttpSession(ServletContext servletContext, String id)@b@  {@b@    this.creationTime = System.currentTimeMillis();@b@@b@    this.lastAccessedTime = System.currentTimeMillis();@b@@b@    this.attributes = new LinkedHashMap();@b@@b@    this.invalid = false;@b@@b@    this.isNew = true;@b@@b@    this.servletContext = new MockServletContext();@b@    this.id = ((id != null) ? id : Integer.toString(nextId++));@b@  }@b@@b@  public long getCreationTime()@b@  {@b@    assertIsValid();@b@    return this.creationTime;@b@  }@b@@b@  public String getId()@b@  {@b@    return this.id;@b@  }@b@@b@  public String changeSessionId()@b@  {@b@    this.id = Integer.toString(nextId++);@b@    return this.id;@b@  }@b@@b@  public void access() {@b@    this.lastAccessedTime = System.currentTimeMillis();@b@    this.isNew = false;@b@  }@b@@b@  public long getLastAccessedTime()@b@  {@b@    assertIsValid();@b@    return this.lastAccessedTime;@b@  }@b@@b@  public ServletContext getServletContext()@b@  {@b@    return this.servletContext;@b@  }@b@@b@  public void setMaxInactiveInterval(int interval)@b@  {@b@    this.maxInactiveInterval = interval;@b@  }@b@@b@  public int getMaxInactiveInterval()@b@  {@b@    return this.maxInactiveInterval;@b@  }@b@@b@  public HttpSessionContext getSessionContext()@b@  {@b@    throw new UnsupportedOperationException("getSessionContext");@b@  }@b@@b@  public Object getAttribute(String name)@b@  {@b@    assertIsValid();@b@    Assert.notNull(name, "Attribute name must not be null");@b@    return this.attributes.get(name);@b@  }@b@@b@  public Object getValue(String name)@b@  {@b@    return getAttribute(name);@b@  }@b@@b@  public Enumeration<String> getAttributeNames()@b@  {@b@    assertIsValid();@b@    return Collections.enumeration(new LinkedHashSet(this.attributes.keySet()));@b@  }@b@@b@  public String[] getValueNames()@b@  {@b@    assertIsValid();@b@    return ((String[])this.attributes.keySet().toArray(new String[this.attributes.size()]));@b@  }@b@@b@  public void setAttribute(String name, Object value)@b@  {@b@    assertIsValid();@b@    Assert.notNull(name, "Attribute name must not be null");@b@    if (value != null) {@b@      this.attributes.put(name, value);@b@      if (value instanceof HttpSessionBindingListener)@b@        ((HttpSessionBindingListener)value).valueBound(new HttpSessionBindingEvent(this, name, value));@b@    }@b@    else@b@    {@b@      removeAttribute(name);@b@    }@b@  }@b@@b@  public void putValue(String name, Object value)@b@  {@b@    setAttribute(name, value);@b@  }@b@@b@  public void removeAttribute(String name)@b@  {@b@    assertIsValid();@b@    Assert.notNull(name, "Attribute name must not be null");@b@    Object value = this.attributes.remove(name);@b@    if (value instanceof HttpSessionBindingListener)@b@      ((HttpSessionBindingListener)value).valueUnbound(new HttpSessionBindingEvent(this, name, value));@b@  }@b@@b@  public void removeValue(String name)@b@  {@b@    removeAttribute(name);@b@  }@b@@b@  public void clearAttributes()@b@  {@b@    for (Iterator it = this.attributes.entrySet().iterator(); it.hasNext(); ) {@b@      Map.Entry entry = (Map.Entry)it.next();@b@      String name = (String)entry.getKey();@b@      Object value = entry.getValue();@b@      it.remove();@b@      if (value instanceof HttpSessionBindingListener)@b@        ((HttpSessionBindingListener)value).valueUnbound(new HttpSessionBindingEvent(this, name, value));@b@    }@b@  }@b@@b@  public void invalidate()@b@  {@b@    assertIsValid();@b@    this.invalid = true;@b@    clearAttributes();@b@  }@b@@b@  public boolean isInvalid() {@b@    return this.invalid;@b@  }@b@@b@  private void assertIsValid()@b@  {@b@    if (isInvalid())@b@      throw new IllegalStateException("The session has already been invalidated");@b@  }@b@@b@  public void setNew(boolean value)@b@  {@b@    this.isNew = value;@b@  }@b@@b@  public boolean isNew()@b@  {@b@    assertIsValid();@b@    return this.isNew;@b@  }@b@@b@  public Serializable serializeState()@b@  {@b@    HashMap state = new HashMap();@b@    for (Iterator it = this.attributes.entrySet().iterator(); it.hasNext(); ) {@b@      Map.Entry entry = (Map.Entry)it.next();@b@      String name = (String)entry.getKey();@b@      Object value = entry.getValue();@b@      it.remove();@b@      if (value instanceof Serializable) {@b@        state.put(name, (Serializable)value);@b@      }@b@      else if (value instanceof HttpSessionBindingListener)@b@        ((HttpSessionBindingListener)value).valueUnbound(new HttpSessionBindingEvent(this, name, value));@b@@b@    }@b@@b@    return state;@b@  }@b@@b@  public void deserializeState(Serializable state)@b@  {@b@    Assert.isTrue(state instanceof Map, "Serialized state needs to be of type [java.util.Map]");@b@    this.attributes.putAll((Map)state);@b@  }@b@}
package org.springframework.mock.web;@b@@b@import java.io.ByteArrayOutputStream;@b@import java.io.IOException;@b@import java.io.OutputStream;@b@import java.io.OutputStreamWriter;@b@import java.io.PrintWriter;@b@import java.io.UnsupportedEncodingException;@b@import java.io.Writer;@b@import java.nio.charset.Charset;@b@import java.text.DateFormat;@b@import java.text.ParseException;@b@import java.text.SimpleDateFormat;@b@import java.util.ArrayList;@b@import java.util.Collection;@b@import java.util.Collections;@b@import java.util.Date;@b@import java.util.List;@b@import java.util.Locale;@b@import java.util.Map;@b@import java.util.TimeZone;@b@import javax.servlet.ServletOutputStream;@b@import javax.servlet.http.Cookie;@b@import javax.servlet.http.HttpServletResponse;@b@import org.springframework.http.MediaType;@b@import org.springframework.util.Assert;@b@import org.springframework.util.LinkedCaseInsensitiveMap;@b@@b@public class MockHttpServletResponse@b@  implements HttpServletResponse@b@{@b@  private static final String CHARSET_PREFIX = "charset=";@b@  private static final String CONTENT_TYPE_HEADER = "Content-Type";@b@  private static final String CONTENT_LENGTH_HEADER = "Content-Length";@b@  private static final String LOCATION_HEADER = "Location";@b@  private static final String DATE_FORMAT = "EEE, dd MMM yyyy HH:mm:ss zzz";@b@  private static final TimeZone GMT = TimeZone.getTimeZone("GMT");@b@  private boolean outputStreamAccessAllowed;@b@  private boolean writerAccessAllowed;@b@  private String characterEncoding;@b@  private boolean charset;@b@  private final ByteArrayOutputStream content;@b@  private final ServletOutputStream outputStream;@b@  private PrintWriter writer;@b@  private long contentLength;@b@  private String contentType;@b@  private int bufferSize;@b@  private boolean committed;@b@  private Locale locale;@b@  private final List<Cookie> cookies;@b@  private final Map<String, HeaderValueHolder> headers;@b@  private int status;@b@  private String errorMessage;@b@  private String forwardedUrl;@b@  private final List<String> includedUrls;@b@@b@  public MockHttpServletResponse()@b@  {@b@    this.outputStreamAccessAllowed = true;@b@@b@    this.writerAccessAllowed = true;@b@@b@    this.characterEncoding = "ISO-8859-1";@b@@b@    this.charset = false;@b@@b@    this.content = new ByteArrayOutputStream(1024);@b@@b@    this.outputStream = new ResponseServletOutputStream(this, this.content);@b@@b@    this.contentLength = 0L;@b@@b@    this.bufferSize = 4096;@b@@b@    this.locale = Locale.getDefault();@b@@b@    this.cookies = new ArrayList();@b@@b@    this.headers = new LinkedCaseInsensitiveMap();@b@@b@    this.status = 200;@b@@b@    this.includedUrls = new ArrayList();@b@  }@b@@b@  public void setOutputStreamAccessAllowed(boolean outputStreamAccessAllowed)@b@  {@b@    this.outputStreamAccessAllowed = outputStreamAccessAllowed;@b@  }@b@@b@  public boolean isOutputStreamAccessAllowed()@b@  {@b@    return this.outputStreamAccessAllowed;@b@  }@b@@b@  public void setWriterAccessAllowed(boolean writerAccessAllowed)@b@  {@b@    this.writerAccessAllowed = writerAccessAllowed;@b@  }@b@@b@  public boolean isWriterAccessAllowed()@b@  {@b@    return this.writerAccessAllowed;@b@  }@b@@b@  public boolean isCharset()@b@  {@b@    return this.charset;@b@  }@b@@b@  public void setCharacterEncoding(String characterEncoding)@b@  {@b@    this.characterEncoding = characterEncoding;@b@    this.charset = true;@b@    updateContentTypeHeader();@b@  }@b@@b@  private void updateContentTypeHeader() {@b@    if (this.contentType != null) {@b@      StringBuilder sb = new StringBuilder(this.contentType);@b@      if ((!(this.contentType.toLowerCase().contains("charset="))) && (this.charset))@b@        sb.append(";").append("charset=").append(this.characterEncoding);@b@@b@      doAddHeaderValue("Content-Type", sb.toString(), true);@b@    }@b@  }@b@@b@  public String getCharacterEncoding()@b@  {@b@    return this.characterEncoding;@b@  }@b@@b@  public ServletOutputStream getOutputStream()@b@  {@b@    if (!(this.outputStreamAccessAllowed))@b@      throw new IllegalStateException("OutputStream access not allowed");@b@@b@    return this.outputStream;@b@  }@b@@b@  public PrintWriter getWriter() throws UnsupportedEncodingException@b@  {@b@    if (!(this.writerAccessAllowed))@b@      throw new IllegalStateException("Writer access not allowed");@b@@b@    if (this.writer == null) {@b@      Writer targetWriter = new OutputStreamWriter(this.content);@b@@b@      this.writer = new ResponsePrintWriter(this, targetWriter);@b@    }@b@    return this.writer;@b@  }@b@@b@  public byte[] getContentAsByteArray() {@b@    flushBuffer();@b@    return this.content.toByteArray();@b@  }@b@@b@  public String getContentAsString() throws UnsupportedEncodingException {@b@    flushBuffer();@b@    return ((this.characterEncoding != null) ? this.content@b@      .toString(this.characterEncoding)@b@       : this.content.toString());@b@  }@b@@b@  public void setContentLength(int contentLength)@b@  {@b@    this.contentLength = contentLength;@b@    doAddHeaderValue("Content-Length", Integer.valueOf(contentLength), true);@b@  }@b@@b@  public int getContentLength() {@b@    return (int)this.contentLength;@b@  }@b@@b@  public void setContentLengthLong(long contentLength) {@b@    this.contentLength = contentLength;@b@    doAddHeaderValue("Content-Length", Long.valueOf(contentLength), true);@b@  }@b@@b@  public long getContentLengthLong() {@b@    return this.contentLength;@b@  }@b@@b@  public void setContentType(String contentType)@b@  {@b@    this.contentType = contentType;@b@    if (contentType != null) {@b@      try {@b@        MediaType mediaType = MediaType.parseMediaType(contentType);@b@        if (mediaType.getCharset() != null) {@b@          this.characterEncoding = mediaType.getCharset().name();@b@          this.charset = true;@b@        }@b@      }@b@      catch (Exception ex)@b@      {@b@        int charsetIndex = contentType.toLowerCase().indexOf("charset=");@b@        if (charsetIndex != -1) {@b@          this.characterEncoding = contentType.substring(charsetIndex + "charset=".length());@b@          this.charset = true;@b@        }@b@      }@b@      updateContentTypeHeader();@b@    }@b@  }@b@@b@  public String getContentType()@b@  {@b@    return this.contentType;@b@  }@b@@b@  public void setBufferSize(int bufferSize)@b@  {@b@    this.bufferSize = bufferSize;@b@  }@b@@b@  public int getBufferSize()@b@  {@b@    return this.bufferSize;@b@  }@b@@b@  public void flushBuffer()@b@  {@b@    setCommitted(true);@b@  }@b@@b@  public void resetBuffer()@b@  {@b@    if (isCommitted())@b@      throw new IllegalStateException("Cannot reset buffer - response is already committed");@b@@b@    this.content.reset();@b@  }@b@@b@  private void setCommittedIfBufferSizeExceeded() {@b@    int bufSize = getBufferSize();@b@    if ((bufSize > 0) && (this.content.size() > bufSize))@b@      setCommitted(true);@b@  }@b@@b@  public void setCommitted(boolean committed)@b@  {@b@    this.committed = committed;@b@  }@b@@b@  public boolean isCommitted()@b@  {@b@    return this.committed;@b@  }@b@@b@  public void reset()@b@  {@b@    resetBuffer();@b@    this.characterEncoding = null;@b@    this.contentLength = 0L;@b@    this.contentType = null;@b@    this.locale = null;@b@    this.cookies.clear();@b@    this.headers.clear();@b@    this.status = 200;@b@    this.errorMessage = null;@b@  }@b@@b@  public void setLocale(Locale locale)@b@  {@b@    this.locale = locale;@b@  }@b@@b@  public Locale getLocale()@b@  {@b@    return this.locale;@b@  }@b@@b@  public void addCookie(Cookie cookie)@b@  {@b@    Assert.notNull(cookie, "Cookie must not be null");@b@    this.cookies.add(cookie);@b@  }@b@@b@  public Cookie[] getCookies() {@b@    return ((Cookie[])this.cookies.toArray(new Cookie[this.cookies.size()]));@b@  }@b@@b@  public Cookie getCookie(String name) {@b@    Assert.notNull(name, "Cookie name must not be null");@b@    for (Cookie cookie : this.cookies)@b@      if (name.equals(cookie.getName()))@b@        return cookie;@b@@b@@b@    return null;@b@  }@b@@b@  public boolean containsHeader(String name)@b@  {@b@    return (HeaderValueHolder.getByName(this.headers, name) != null);@b@  }@b@@b@  public Collection<String> getHeaderNames()@b@  {@b@    return this.headers.keySet();@b@  }@b@@b@  public String getHeader(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    return ((header != null) ? header.getStringValue() : null);@b@  }@b@@b@  public List<String> getHeaders(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    if (header != null) {@b@      return header.getStringValues();@b@    }@b@@b@    return Collections.emptyList();@b@  }@b@@b@  public Object getHeaderValue(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    return ((header != null) ? header.getValue() : null);@b@  }@b@@b@  public List<Object> getHeaderValues(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    if (header != null) {@b@      return header.getValues();@b@    }@b@@b@    return Collections.emptyList();@b@  }@b@@b@  public String encodeURL(String url)@b@  {@b@    return url;@b@  }@b@@b@  public String encodeRedirectURL(String url)@b@  {@b@    return encodeURL(url);@b@  }@b@@b@  @Deprecated@b@  public String encodeUrl(String url)@b@  {@b@    return encodeURL(url);@b@  }@b@@b@  @Deprecated@b@  public String encodeRedirectUrl(String url)@b@  {@b@    return encodeRedirectURL(url);@b@  }@b@@b@  public void sendError(int status, String errorMessage) throws IOException@b@  {@b@    if (isCommitted())@b@      throw new IllegalStateException("Cannot set error status - response is already committed");@b@@b@    this.status = status;@b@    this.errorMessage = errorMessage;@b@    setCommitted(true);@b@  }@b@@b@  public void sendError(int status) throws IOException@b@  {@b@    if (isCommitted())@b@      throw new IllegalStateException("Cannot set error status - response is already committed");@b@@b@    this.status = status;@b@    setCommitted(true);@b@  }@b@@b@  public void sendRedirect(String url) throws IOException@b@  {@b@    if (isCommitted())@b@      throw new IllegalStateException("Cannot send redirect - response is already committed");@b@@b@    Assert.notNull(url, "Redirect URL must not be null");@b@    setHeader("Location", url);@b@    setStatus(302);@b@    setCommitted(true);@b@  }@b@@b@  public String getRedirectedUrl() {@b@    return getHeader("Location");@b@  }@b@@b@  public void setDateHeader(String name, long value)@b@  {@b@    setHeaderValue(name, formatDate(value));@b@  }@b@@b@  public void addDateHeader(String name, long value)@b@  {@b@    addHeaderValue(name, formatDate(value));@b@  }@b@@b@  public long getDateHeader(String name) {@b@    String headerValue = getHeader(name);@b@    if (headerValue == null)@b@      return -1L;@b@    try@b@    {@b@      return newDateFormat().parse(getHeader(name)).getTime();@b@    }@b@    catch (ParseException ex) {@b@      throw new IllegalArgumentException(new StringBuilder().append("Value for header '").append(name).append("' is not a valid Date: ").append(headerValue).toString());@b@    }@b@  }@b@@b@  private String formatDate(long date)@b@  {@b@    return newDateFormat().format(new Date(date));@b@  }@b@@b@  private DateFormat newDateFormat() {@b@    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US);@b@    dateFormat.setTimeZone(GMT);@b@    return dateFormat;@b@  }@b@@b@  public void setHeader(String name, String value)@b@  {@b@    setHeaderValue(name, value);@b@  }@b@@b@  public void addHeader(String name, String value)@b@  {@b@    addHeaderValue(name, value);@b@  }@b@@b@  public void setIntHeader(String name, int value)@b@  {@b@    setHeaderValue(name, Integer.valueOf(value));@b@  }@b@@b@  public void addIntHeader(String name, int value)@b@  {@b@    addHeaderValue(name, Integer.valueOf(value));@b@  }@b@@b@  private void setHeaderValue(String name, Object value) {@b@    if (setSpecialHeader(name, value))@b@      return;@b@@b@    doAddHeaderValue(name, value, true);@b@  }@b@@b@  private void addHeaderValue(String name, Object value) {@b@    if (setSpecialHeader(name, value))@b@      return;@b@@b@    doAddHeaderValue(name, value, false);@b@  }@b@@b@  private boolean setSpecialHeader(String name, Object value) {@b@    if ("Content-Type".equalsIgnoreCase(name)) {@b@      setContentType(value.toString());@b@      return true;@b@    }@b@    if ("Content-Length".equalsIgnoreCase(name)) {@b@      setContentLength((value instanceof Number) ? ((Number)value).intValue() : @b@        Integer.parseInt(value@b@        .toString()));@b@      return true;@b@    }@b@@b@    return false;@b@  }@b@@b@  private void doAddHeaderValue(String name, Object value, boolean replace)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    Assert.notNull(value, "Header value must not be null");@b@    if (header == null) {@b@      header = new HeaderValueHolder();@b@      this.headers.put(name, header);@b@    }@b@    if (replace) {@b@      header.setValue(value);@b@    }@b@    else@b@      header.addValue(value);@b@  }@b@@b@  public void setStatus(int status)@b@  {@b@    if (!(isCommitted()))@b@      this.status = status;@b@  }@b@@b@  @Deprecated@b@  public void setStatus(int status, String errorMessage)@b@  {@b@    if (!(isCommitted())) {@b@      this.status = status;@b@      this.errorMessage = errorMessage;@b@    }@b@  }@b@@b@  public int getStatus()@b@  {@b@    return this.status;@b@  }@b@@b@  public String getErrorMessage() {@b@    return this.errorMessage;@b@  }@b@@b@  public void setForwardedUrl(String forwardedUrl)@b@  {@b@    this.forwardedUrl = forwardedUrl;@b@  }@b@@b@  public String getForwardedUrl() {@b@    return this.forwardedUrl;@b@  }@b@@b@  public void setIncludedUrl(String includedUrl) {@b@    this.includedUrls.clear();@b@    if (includedUrl != null)@b@      this.includedUrls.add(includedUrl);@b@  }@b@@b@  public String getIncludedUrl()@b@  {@b@    int count = this.includedUrls.size();@b@    if (count > 1) {@b@      throw new IllegalStateException(new StringBuilder().append("More than 1 URL included - check getIncludedUrls instead: ").append(this.includedUrls).toString());@b@    }@b@@b@    return ((count == 1) ? (String)this.includedUrls.get(0) : null);@b@  }@b@@b@  public void addIncludedUrl(String includedUrl) {@b@    Assert.notNull(includedUrl, "Included URL must not be null");@b@    this.includedUrls.add(includedUrl);@b@  }@b@@b@  public List<String> getIncludedUrls() {@b@    return this.includedUrls;@b@  }@b@@b@  private class ResponsePrintWriter extends PrintWriter@b@  {@b@    public ResponsePrintWriter(, Writer paramWriter)@b@    {@b@      super(out, true);@b@    }@b@@b@    public void write(, int off, int len)@b@    {@b@      super.write(buf, off, len);@b@      super.flush();@b@      MockHttpServletResponse.access$000(this.this$0);@b@    }@b@@b@    public void write(, int off, int len)@b@    {@b@      super.write(s, off, len);@b@      super.flush();@b@      MockHttpServletResponse.access$000(this.this$0);@b@    }@b@@b@    public void write()@b@    {@b@      super.write(c);@b@      super.flush();@b@      MockHttpServletResponse.access$000(this.this$0);@b@    }@b@@b@    public void flush()@b@    {@b@      super.flush();@b@      this.this$0.setCommitted(true);@b@    }@b@  }@b@@b@  private class ResponseServletOutputStream extends DelegatingServletOutputStream@b@  {@b@    public ResponseServletOutputStream(, OutputStream paramOutputStream)@b@    {@b@      super(out);@b@    }@b@@b@    public void write() throws IOException@b@    {@b@      super.write(b);@b@      super.flush();@b@      MockHttpServletResponse.access$000(this.this$0);@b@    }@b@@b@    public void flush() throws IOException@b@    {@b@      super.flush();@b@      this.this$0.setCommitted(true);@b@    }@b@  }@b@}
package org.springframework.mock.web;@b@@b@import java.io.BufferedReader;@b@import java.io.ByteArrayInputStream;@b@import java.io.IOException;@b@import java.io.InputStream;@b@import java.io.InputStreamReader;@b@import java.io.Reader;@b@import java.io.StringReader;@b@import java.io.UnsupportedEncodingException;@b@import java.nio.charset.Charset;@b@import java.security.Principal;@b@import java.text.ParseException;@b@import java.text.SimpleDateFormat;@b@import java.util.Collection;@b@import java.util.Collections;@b@import java.util.Date;@b@import java.util.Enumeration;@b@import java.util.HashSet;@b@import java.util.LinkedHashMap;@b@import java.util.LinkedHashSet;@b@import java.util.LinkedList;@b@import java.util.List;@b@import java.util.Locale;@b@import java.util.Map;@b@import java.util.Set;@b@import java.util.TimeZone;@b@import javax.servlet.AsyncContext;@b@import javax.servlet.DispatcherType;@b@import javax.servlet.RequestDispatcher;@b@import javax.servlet.ServletException;@b@import javax.servlet.ServletInputStream;@b@import javax.servlet.ServletRequest;@b@import javax.servlet.ServletResponse;@b@import javax.servlet.http.Cookie;@b@import javax.servlet.http.HttpServletRequest;@b@import javax.servlet.http.HttpServletResponse;@b@import javax.servlet.http.HttpSession;@b@import javax.servlet.http.Part;@b@import org.springframework.http.MediaType;@b@import org.springframework.util.Assert;@b@import org.springframework.util.LinkedCaseInsensitiveMap;@b@import org.springframework.util.LinkedMultiValueMap;@b@import org.springframework.util.MultiValueMap;@b@import org.springframework.util.StreamUtils;@b@import org.springframework.util.StringUtils;@b@@b@public class MockHttpServletRequest@b@  implements HttpServletRequest@b@{@b@  private static final String HTTP = "http";@b@  private static final String HTTPS = "https";@b@  private static final String CONTENT_TYPE_HEADER = "Content-Type";@b@  private static final String HOST_HEADER = "Host";@b@  private static final String CHARSET_PREFIX = "charset=";@b@  private static final TimeZone GMT = TimeZone.getTimeZone("GMT");@b@  private static final ServletInputStream EMPTY_SERVLET_INPUT_STREAM = new DelegatingServletInputStream(StreamUtils.emptyInput());@b@  private static final BufferedReader EMPTY_BUFFERED_READER = new BufferedReader(new StringReader(""));@b@  private static final String[] DATE_FORMATS = { "EEE, dd MMM yyyy HH:mm:ss zzz", "EEE, dd-MMM-yy HH:mm:ss zzz", "EEE MMM dd HH:mm:ss yyyy" };@b@  public static final String DEFAULT_PROTOCOL = "HTTP/1.1";@b@  public static final String DEFAULT_SCHEME = "http";@b@  public static final String DEFAULT_SERVER_ADDR = "127.0.0.1";@b@  public static final String DEFAULT_SERVER_NAME = "localhost";@b@  public static final int DEFAULT_SERVER_PORT = 80;@b@  public static final String DEFAULT_REMOTE_ADDR = "127.0.0.1";@b@  public static final String DEFAULT_REMOTE_HOST = "localhost";@b@  private final javax.servlet.ServletContext servletContext;@b@  private boolean active;@b@  private final Map<String, Object> attributes;@b@  private String characterEncoding;@b@  private byte[] content;@b@  private String contentType;@b@  private final Map<String, String[]> parameters;@b@  private String protocol;@b@  private String scheme;@b@  private String serverName;@b@  private int serverPort;@b@  private String remoteAddr;@b@  private String remoteHost;@b@  private final List<Locale> locales;@b@  private boolean secure;@b@  private int remotePort;@b@  private String localName;@b@  private String localAddr;@b@  private int localPort;@b@  private boolean asyncStarted;@b@  private boolean asyncSupported;@b@  private MockAsyncContext asyncContext;@b@  private DispatcherType dispatcherType;@b@  private String authType;@b@  private Cookie[] cookies;@b@  private final Map<String, HeaderValueHolder> headers;@b@  private String method;@b@  private String pathInfo;@b@  private String contextPath;@b@  private String queryString;@b@  private String remoteUser;@b@  private final Set<String> userRoles;@b@  private Principal userPrincipal;@b@  private String requestedSessionId;@b@  private String requestURI;@b@  private String servletPath;@b@  private HttpSession session;@b@  private boolean requestedSessionIdValid;@b@  private boolean requestedSessionIdFromCookie;@b@  private boolean requestedSessionIdFromURL;@b@  private final MultiValueMap<String, Part> parts;@b@@b@  public MockHttpServletRequest()@b@  {@b@    this(null, "", "");@b@  }@b@@b@  public MockHttpServletRequest(String method, String requestURI)@b@  {@b@    this(null, method, requestURI);@b@  }@b@@b@  public MockHttpServletRequest(javax.servlet.ServletContext servletContext)@b@  {@b@    this(servletContext, "", "");@b@  }@b@@b@  public MockHttpServletRequest(javax.servlet.ServletContext servletContext, String method, String requestURI)@b@  {@b@    this.active = true;@b@@b@    this.attributes = new LinkedHashMap();@b@@b@    this.parameters = new LinkedHashMap();@b@@b@    this.protocol = "HTTP/1.1";@b@@b@    this.scheme = "http";@b@@b@    this.serverName = "localhost";@b@@b@    this.serverPort = 80;@b@@b@    this.remoteAddr = "127.0.0.1";@b@@b@    this.remoteHost = "localhost";@b@@b@    this.locales = new LinkedList();@b@@b@    this.secure = false;@b@@b@    this.remotePort = 80;@b@@b@    this.localName = "localhost";@b@@b@    this.localAddr = "127.0.0.1";@b@@b@    this.localPort = 80;@b@@b@    this.asyncStarted = false;@b@@b@    this.asyncSupported = false;@b@@b@    this.dispatcherType = DispatcherType.REQUEST;@b@@b@    this.headers = new LinkedCaseInsensitiveMap();@b@@b@    this.contextPath = "";@b@@b@    this.userRoles = new HashSet();@b@@b@    this.servletPath = "";@b@@b@    this.requestedSessionIdValid = true;@b@@b@    this.requestedSessionIdFromCookie = true;@b@@b@    this.requestedSessionIdFromURL = false;@b@@b@    this.parts = new LinkedMultiValueMap();@b@@b@    this.servletContext = new MockServletContext();@b@    this.method = method;@b@    this.requestURI = requestURI;@b@    this.locales.add(Locale.ENGLISH);@b@  }@b@@b@  public javax.servlet.ServletContext getServletContext()@b@  {@b@    return this.servletContext;@b@  }@b@@b@  public boolean isActive()@b@  {@b@    return this.active;@b@  }@b@@b@  public void close()@b@  {@b@    this.active = false;@b@  }@b@@b@  public void invalidate()@b@  {@b@    close();@b@    clearAttributes();@b@  }@b@@b@  protected void checkActive()@b@    throws IllegalStateException@b@  {@b@    if (!(this.active))@b@      throw new IllegalStateException("Request is not active anymore");@b@  }@b@@b@  public Object getAttribute(String name)@b@  {@b@    checkActive();@b@    return this.attributes.get(name);@b@  }@b@@b@  public Enumeration<String> getAttributeNames()@b@  {@b@    checkActive();@b@    return Collections.enumeration(new LinkedHashSet(this.attributes.keySet()));@b@  }@b@@b@  public String getCharacterEncoding()@b@  {@b@    return this.characterEncoding;@b@  }@b@@b@  public void setCharacterEncoding(String characterEncoding)@b@  {@b@    this.characterEncoding = characterEncoding;@b@    updateContentTypeHeader();@b@  }@b@@b@  private void updateContentTypeHeader() {@b@    if (StringUtils.hasLength(this.contentType)) {@b@      StringBuilder sb = new StringBuilder(this.contentType);@b@      if ((!(this.contentType.toLowerCase().contains("charset="))) && @b@        (StringUtils.hasLength(this.characterEncoding)))@b@      {@b@        sb.append(";").append("charset=").append(this.characterEncoding);@b@      }@b@      doAddHeaderValue("Content-Type", sb.toString(), true);@b@    }@b@  }@b@@b@  public void setContent(byte[] content) {@b@    this.content = content;@b@  }@b@@b@  public int getContentLength()@b@  {@b@    return ((this.content != null) ? this.content.length : -1);@b@  }@b@@b@  public long getContentLengthLong() {@b@    return getContentLength();@b@  }@b@@b@  public void setContentType(String contentType) {@b@    this.contentType = contentType;@b@    if (contentType != null) {@b@      try {@b@        MediaType mediaType = MediaType.parseMediaType(contentType);@b@        if (mediaType.getCharset() != null)@b@          this.characterEncoding = mediaType.getCharset().name();@b@@b@      }@b@      catch (Exception ex)@b@      {@b@        int charsetIndex = contentType.toLowerCase().indexOf("charset=");@b@        if (charsetIndex != -1)@b@          this.characterEncoding = contentType.substring(charsetIndex + "charset=".length());@b@      }@b@@b@      updateContentTypeHeader();@b@    }@b@  }@b@@b@  public String getContentType()@b@  {@b@    return this.contentType;@b@  }@b@@b@  public ServletInputStream getInputStream()@b@  {@b@    if (this.content != null) {@b@      return new DelegatingServletInputStream(new ByteArrayInputStream(this.content));@b@    }@b@@b@    return EMPTY_SERVLET_INPUT_STREAM;@b@  }@b@@b@  public void setParameter(String name, String value)@b@  {@b@    setParameter(name, new String[] { value });@b@  }@b@@b@  public void setParameter(String name, String[] values)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    this.parameters.put(name, values);@b@  }@b@@b@  public void setParameters(Map<String, ?> params)@b@  {@b@    Assert.notNull(params, "Parameter map must not be null");@b@    for (String key : params.keySet()) {@b@      Object value = params.get(key);@b@      if (value instanceof String) {@b@        setParameter(key, (String)value);@b@      }@b@      else if (value instanceof String[]) {@b@        setParameter(key, (String[])(String[])value);@b@      }@b@      else@b@      {@b@        throw new IllegalArgumentException(new StringBuilder().append("Parameter map value must be single value  or array of type [")@b@          .append(String.class@b@          .getName()).append("]").toString());@b@      }@b@    }@b@  }@b@@b@  public void addParameter(String name, String value)@b@  {@b@    addParameter(name, new String[] { value });@b@  }@b@@b@  public void addParameter(String name, String[] values)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    String[] oldArr = (String[])this.parameters.get(name);@b@    if (oldArr != null) {@b@      String[] newArr = new String[oldArr.length + values.length];@b@      System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);@b@      System.arraycopy(values, 0, newArr, oldArr.length, values.length);@b@      this.parameters.put(name, newArr);@b@    }@b@    else {@b@      this.parameters.put(name, values);@b@    }@b@  }@b@@b@  public void addParameters(Map<String, ?> params)@b@  {@b@    Assert.notNull(params, "Parameter map must not be null");@b@    for (String key : params.keySet()) {@b@      Object value = params.get(key);@b@      if (value instanceof String) {@b@        addParameter(key, (String)value);@b@      }@b@      else if (value instanceof String[]) {@b@        addParameter(key, (String[])(String[])value);@b@      }@b@      else@b@      {@b@        throw new IllegalArgumentException(new StringBuilder().append("Parameter map value must be single value  or array of type [")@b@          .append(String.class@b@          .getName()).append("]").toString());@b@      }@b@    }@b@  }@b@@b@  public void removeParameter(String name)@b@  {@b@    Assert.notNull(name, "Parameter name must not be null");@b@    this.parameters.remove(name);@b@  }@b@@b@  public void removeAllParameters()@b@  {@b@    this.parameters.clear();@b@  }@b@@b@  public String getParameter(String name)@b@  {@b@    String[] arr = (name != null) ? (String[])this.parameters.get(name) : null;@b@    return (((arr != null) && (arr.length > 0)) ? arr[0] : null);@b@  }@b@@b@  public Enumeration<String> getParameterNames()@b@  {@b@    return Collections.enumeration(this.parameters.keySet());@b@  }@b@@b@  public String[] getParameterValues(String name)@b@  {@b@    return ((name != null) ? (String[])this.parameters.get(name) : null);@b@  }@b@@b@  public Map<String, String[]> getParameterMap()@b@  {@b@    return Collections.unmodifiableMap(this.parameters);@b@  }@b@@b@  public void setProtocol(String protocol) {@b@    this.protocol = protocol;@b@  }@b@@b@  public String getProtocol()@b@  {@b@    return this.protocol;@b@  }@b@@b@  public void setScheme(String scheme) {@b@    this.scheme = scheme;@b@  }@b@@b@  public String getScheme()@b@  {@b@    return this.scheme;@b@  }@b@@b@  public void setServerName(String serverName) {@b@    this.serverName = serverName;@b@  }@b@@b@  public String getServerName()@b@  {@b@    String host = getHeader("Host");@b@    if (host != null) {@b@      host = host.trim();@b@      if (host.startsWith("[")) {@b@        host = host.substring(1, host.indexOf(93));@b@      }@b@      else if (host.contains(":"))@b@        host = host.substring(0, host.indexOf(58));@b@@b@      return host;@b@    }@b@@b@    return this.serverName;@b@  }@b@@b@  public void setServerPort(int serverPort) {@b@    this.serverPort = serverPort;@b@  }@b@@b@  public int getServerPort()@b@  {@b@    String host = getHeader("Host");@b@    if (host != null) {@b@      int idx;@b@      host = host.trim();@b@@b@      if (host.startsWith("[")) {@b@        idx = host.indexOf(58, host.indexOf(93));@b@      }@b@      else@b@        idx = host.indexOf(58);@b@@b@      if (idx != -1) {@b@        return Integer.parseInt(host.substring(idx + 1));@b@      }@b@@b@    }@b@@b@    return this.serverPort;@b@  }@b@@b@  public BufferedReader getReader() throws UnsupportedEncodingException@b@  {@b@    if (this.content != null) {@b@      InputStream sourceStream = new ByteArrayInputStream(this.content);@b@      Reader sourceReader = new InputStreamReader(sourceStream);@b@@b@      return new BufferedReader(sourceReader);@b@    }@b@@b@    return EMPTY_BUFFERED_READER;@b@  }@b@@b@  public void setRemoteAddr(String remoteAddr)@b@  {@b@    this.remoteAddr = remoteAddr;@b@  }@b@@b@  public String getRemoteAddr()@b@  {@b@    return this.remoteAddr;@b@  }@b@@b@  public void setRemoteHost(String remoteHost) {@b@    this.remoteHost = remoteHost;@b@  }@b@@b@  public String getRemoteHost()@b@  {@b@    return this.remoteHost;@b@  }@b@@b@  public void setAttribute(String name, Object value)@b@  {@b@    checkActive();@b@    Assert.notNull(name, "Attribute name must not be null");@b@    if (value != null) {@b@      this.attributes.put(name, value);@b@    }@b@    else@b@      this.attributes.remove(name);@b@  }@b@@b@  public void removeAttribute(String name)@b@  {@b@    checkActive();@b@    Assert.notNull(name, "Attribute name must not be null");@b@    this.attributes.remove(name);@b@  }@b@@b@  public void clearAttributes()@b@  {@b@    this.attributes.clear();@b@  }@b@@b@  public void addPreferredLocale(Locale locale)@b@  {@b@    Assert.notNull(locale, "Locale must not be null");@b@    this.locales.add(0, locale);@b@  }@b@@b@  public void setPreferredLocales(List<Locale> locales)@b@  {@b@    Assert.notEmpty(locales, "Locale list must not be empty");@b@    this.locales.clear();@b@    this.locales.addAll(locales);@b@  }@b@@b@  public Locale getLocale()@b@  {@b@    return ((Locale)this.locales.get(0));@b@  }@b@@b@  public Enumeration<Locale> getLocales()@b@  {@b@    return Collections.enumeration(this.locales);@b@  }@b@@b@  public void setSecure(boolean secure)@b@  {@b@    this.secure = secure;@b@  }@b@@b@  public boolean isSecure()@b@  {@b@    return ((this.secure) || ("https".equalsIgnoreCase(this.scheme)));@b@  }@b@@b@  public RequestDispatcher getRequestDispatcher(String path)@b@  {@b@    return new MockRequestDispatcher(path);@b@  }@b@@b@  @Deprecated@b@  public String getRealPath(String path)@b@  {@b@    return this.servletContext.getRealPath(path);@b@  }@b@@b@  public void setRemotePort(int remotePort) {@b@    this.remotePort = remotePort;@b@  }@b@@b@  public int getRemotePort()@b@  {@b@    return this.remotePort;@b@  }@b@@b@  public void setLocalName(String localName) {@b@    this.localName = localName;@b@  }@b@@b@  public String getLocalName()@b@  {@b@    return this.localName;@b@  }@b@@b@  public void setLocalAddr(String localAddr) {@b@    this.localAddr = localAddr;@b@  }@b@@b@  public String getLocalAddr()@b@  {@b@    return this.localAddr;@b@  }@b@@b@  public void setLocalPort(int localPort) {@b@    this.localPort = localPort;@b@  }@b@@b@  public int getLocalPort()@b@  {@b@    return this.localPort;@b@  }@b@@b@  public AsyncContext startAsync()@b@  {@b@    return startAsync(this, null);@b@  }@b@@b@  public AsyncContext startAsync(ServletRequest request, ServletResponse response)@b@  {@b@    if (!(this.asyncSupported))@b@      throw new IllegalStateException("Async not supported");@b@@b@    this.asyncStarted = true;@b@    this.asyncContext = new MockAsyncContext(request, response);@b@    return this.asyncContext;@b@  }@b@@b@  public void setAsyncStarted(boolean asyncStarted) {@b@    this.asyncStarted = asyncStarted;@b@  }@b@@b@  public boolean isAsyncStarted()@b@  {@b@    return this.asyncStarted;@b@  }@b@@b@  public void setAsyncSupported(boolean asyncSupported) {@b@    this.asyncSupported = asyncSupported;@b@  }@b@@b@  public boolean isAsyncSupported()@b@  {@b@    return this.asyncSupported;@b@  }@b@@b@  public void setAsyncContext(MockAsyncContext asyncContext) {@b@    this.asyncContext = asyncContext;@b@  }@b@@b@  public AsyncContext getAsyncContext()@b@  {@b@    return this.asyncContext;@b@  }@b@@b@  public void setDispatcherType(DispatcherType dispatcherType) {@b@    this.dispatcherType = dispatcherType;@b@  }@b@@b@  public DispatcherType getDispatcherType()@b@  {@b@    return this.dispatcherType;@b@  }@b@@b@  public void setAuthType(String authType)@b@  {@b@    this.authType = authType;@b@  }@b@@b@  public String getAuthType()@b@  {@b@    return this.authType;@b@  }@b@@b@  public void setCookies(Cookie[] cookies) {@b@    this.cookies = cookies;@b@  }@b@@b@  public Cookie[] getCookies()@b@  {@b@    return this.cookies;@b@  }@b@@b@  public void addHeader(String name, Object value)@b@  {@b@    if (("Content-Type".equalsIgnoreCase(name)) && (!(this.headers.containsKey("Content-Type")))) {@b@      setContentType(value.toString());@b@    }@b@    else@b@      doAddHeaderValue(name, value, false);@b@  }@b@@b@  private void doAddHeaderValue(String name, Object value, boolean replace)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    Assert.notNull(value, "Header value must not be null");@b@    if ((header == null) || (replace)) {@b@      header = new HeaderValueHolder();@b@      this.headers.put(name, header);@b@    }@b@    if (value instanceof Collection) {@b@      header.addValues((Collection)value);@b@    }@b@    else if (value.getClass().isArray()) {@b@      header.addValueArray(value);@b@    }@b@    else@b@      header.addValue(value);@b@  }@b@@b@  public long getDateHeader(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    Object value = (header != null) ? header.getValue() : null;@b@    if (value instanceof Date)@b@      return ((Date)value).getTime();@b@@b@    if (value instanceof Number)@b@      return ((Number)value).longValue();@b@@b@    if (value instanceof String)@b@      return parseDateHeader(name, (String)value);@b@@b@    if (value != null) {@b@      throw new IllegalArgumentException(new StringBuilder().append("Value for header '").append(name).append("' is not a Date, Number, or String: ").append(value).toString());@b@    }@b@@b@    return -1L;@b@  }@b@@b@  private long parseDateHeader(String name, String value)@b@  {@b@    SimpleDateFormat simpleDateFormat;@b@    String[] arrayOfString = DATE_FORMATS; int i = arrayOfString.length; int j = 0; if (j < i) { String dateFormat = arrayOfString[j];@b@      simpleDateFormat = new SimpleDateFormat(dateFormat, Locale.US);@b@      simpleDateFormat.setTimeZone(GMT); }@b@    try {@b@      return simpleDateFormat.parse(value).getTime();@b@    }@b@    catch (ParseException localParseException)@b@    {@b@      while (true) {@b@        ++j;@b@      }@b@@b@      throw new IllegalArgumentException(new StringBuilder().append("Cannot parse date value '").append(value).append("' for '").append(name).append("' header").toString());@b@    }@b@  }@b@@b@  public String getHeader(String name) {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    return ((header != null) ? header.getStringValue() : null);@b@  }@b@@b@  public Enumeration<String> getHeaders(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    return Collections.enumeration(new LinkedList());@b@  }@b@@b@  public Enumeration<String> getHeaderNames()@b@  {@b@    return Collections.enumeration(this.headers.keySet());@b@  }@b@@b@  public int getIntHeader(String name)@b@  {@b@    HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);@b@    Object value = (header != null) ? header.getValue() : null;@b@    if (value instanceof Number)@b@      return ((Number)value).intValue();@b@@b@    if (value instanceof String)@b@      return Integer.parseInt((String)value);@b@@b@    if (value != null) {@b@      throw new NumberFormatException(new StringBuilder().append("Value for header '").append(name).append("' is not a Number: ").append(value).toString());@b@    }@b@@b@    return -1;@b@  }@b@@b@  public void setMethod(String method)@b@  {@b@    this.method = method;@b@  }@b@@b@  public String getMethod()@b@  {@b@    return this.method;@b@  }@b@@b@  public void setPathInfo(String pathInfo) {@b@    this.pathInfo = pathInfo;@b@  }@b@@b@  public String getPathInfo()@b@  {@b@    return this.pathInfo;@b@  }@b@@b@  public String getPathTranslated()@b@  {@b@    return ((this.pathInfo != null) ? getRealPath(this.pathInfo) : null);@b@  }@b@@b@  public void setContextPath(String contextPath) {@b@    this.contextPath = contextPath;@b@  }@b@@b@  public String getContextPath()@b@  {@b@    return this.contextPath;@b@  }@b@@b@  public void setQueryString(String queryString) {@b@    this.queryString = queryString;@b@  }@b@@b@  public String getQueryString()@b@  {@b@    return this.queryString;@b@  }@b@@b@  public void setRemoteUser(String remoteUser) {@b@    this.remoteUser = remoteUser;@b@  }@b@@b@  public String getRemoteUser()@b@  {@b@    return this.remoteUser;@b@  }@b@@b@  public void addUserRole(String role) {@b@    this.userRoles.add(role);@b@  }@b@@b@  public boolean isUserInRole(String role)@b@  {@b@    return ((this.userRoles.contains(role)) || ((this.servletContext instanceof MockServletContext) && @b@      (((MockServletContext)this.servletContext)@b@      .getDeclaredRoles().contains(role))));@b@  }@b@@b@  public void setUserPrincipal(Principal userPrincipal) {@b@    this.userPrincipal = userPrincipal;@b@  }@b@@b@  public Principal getUserPrincipal()@b@  {@b@    return this.userPrincipal;@b@  }@b@@b@  public void setRequestedSessionId(String requestedSessionId) {@b@    this.requestedSessionId = requestedSessionId;@b@  }@b@@b@  public String getRequestedSessionId()@b@  {@b@    return this.requestedSessionId;@b@  }@b@@b@  public void setRequestURI(String requestURI) {@b@    this.requestURI = requestURI;@b@  }@b@@b@  public String getRequestURI()@b@  {@b@    return this.requestURI;@b@  }@b@@b@  public StringBuffer getRequestURL()@b@  {@b@    String scheme = getScheme();@b@    String server = getServerName();@b@    int port = getServerPort();@b@    String uri = getRequestURI();@b@@b@    StringBuffer url = new StringBuffer(scheme).append("://").append(server);@b@    if ((port > 0) && (((("http".equalsIgnoreCase(scheme)) && (port != 80)) || (@b@      ("https"@b@      .equalsIgnoreCase(scheme)) && @b@      (port != 443)))))@b@      url.append(':').append(port);@b@@b@    if (StringUtils.hasText(uri))@b@      url.append(uri);@b@@b@    return url;@b@  }@b@@b@  public void setServletPath(String servletPath) {@b@    this.servletPath = servletPath;@b@  }@b@@b@  public String getServletPath()@b@  {@b@    return this.servletPath;@b@  }@b@@b@  public void setSession(HttpSession session) {@b@    this.session = session;@b@    if (session instanceof MockHttpSession) {@b@      MockHttpSession mockSession = (MockHttpSession)session;@b@      mockSession.access();@b@    }@b@  }@b@@b@  public HttpSession getSession(boolean create)@b@  {@b@    checkActive();@b@@b@    if ((this.session instanceof MockHttpSession) && (((MockHttpSession)this.session).isInvalid())) {@b@      this.session = null;@b@    }@b@@b@    if ((this.session == null) && (create))@b@      this.session = new MockHttpSession(this.servletContext);@b@@b@    return this.session;@b@  }@b@@b@  public HttpSession getSession()@b@  {@b@    return getSession(true);@b@  }@b@@b@  public String changeSessionId()@b@  {@b@    Assert.isTrue(this.session != null, "The request does not have a session");@b@    if (this.session instanceof MockHttpSession)@b@      return ((MockHttpSession)this.session).changeSessionId();@b@@b@    return this.session.getId();@b@  }@b@@b@  public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {@b@    this.requestedSessionIdValid = requestedSessionIdValid;@b@  }@b@@b@  public boolean isRequestedSessionIdValid()@b@  {@b@    return this.requestedSessionIdValid;@b@  }@b@@b@  public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) {@b@    this.requestedSessionIdFromCookie = requestedSessionIdFromCookie;@b@  }@b@@b@  public boolean isRequestedSessionIdFromCookie()@b@  {@b@    return this.requestedSessionIdFromCookie;@b@  }@b@@b@  public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) {@b@    this.requestedSessionIdFromURL = requestedSessionIdFromURL;@b@  }@b@@b@  public boolean isRequestedSessionIdFromURL()@b@  {@b@    return this.requestedSessionIdFromURL;@b@  }@b@@b@  @Deprecated@b@  public boolean isRequestedSessionIdFromUrl()@b@  {@b@    return isRequestedSessionIdFromURL();@b@  }@b@@b@  public boolean authenticate(HttpServletResponse response) throws IOException, ServletException@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public void login(String username, String password) throws ServletException@b@  {@b@    throw new UnsupportedOperationException();@b@  }@b@@b@  public void logout() throws ServletException@b@  {@b@    this.userPrincipal = null;@b@    this.remoteUser = null;@b@    this.authType = null;@b@  }@b@@b@  public void addPart(Part part) {@b@    this.parts.add(part.getName(), part);@b@  }@b@@b@  public Part getPart(String name) throws IOException, ServletException@b@  {@b@    return ((Part)this.parts.getFirst(name));@b@  }@b@@b@  public Collection<Part> getParts() throws IOException, ServletException@b@  {@b@    List result = new LinkedList();@b@    for (List list : this.parts.values())@b@      result.addAll(list);@b@@b@    return result;@b@  }@b@}

3. PageContext、JspWriter类

package org.springframework.mock.web;@b@@b@import java.io.IOException;@b@import java.io.UnsupportedEncodingException;@b@import java.util.Collections;@b@import java.util.Enumeration;@b@import java.util.LinkedHashMap;@b@import java.util.LinkedHashSet;@b@import java.util.Map;@b@import javax.el.ELContext;@b@import javax.servlet.RequestDispatcher;@b@import javax.servlet.Servlet;@b@import javax.servlet.ServletConfig;@b@import javax.servlet.ServletContext;@b@import javax.servlet.ServletException;@b@import javax.servlet.ServletRequest;@b@import javax.servlet.ServletResponse;@b@import javax.servlet.http.HttpServletRequest;@b@import javax.servlet.http.HttpServletResponse;@b@import javax.servlet.http.HttpSession;@b@import javax.servlet.jsp.JspWriter;@b@import javax.servlet.jsp.PageContext;@b@import javax.servlet.jsp.el.ExpressionEvaluator;@b@import javax.servlet.jsp.el.VariableResolver;@b@import org.springframework.util.Assert;@b@@b@public class MockPageContext extends PageContext@b@{@b@  private final ServletContext servletContext;@b@  private final HttpServletRequest request;@b@  private final HttpServletResponse response;@b@  private final ServletConfig servletConfig;@b@  private final Map<String, Object> attributes;@b@  private JspWriter out;@b@@b@  public MockPageContext()@b@  {@b@    this(null, null, null, null);@b@  }@b@@b@  public MockPageContext(ServletContext servletContext)@b@  {@b@    this(servletContext, null, null, null);@b@  }@b@@b@  public MockPageContext(ServletContext servletContext, HttpServletRequest request)@b@  {@b@    this(servletContext, request, null, null);@b@  }@b@@b@  public MockPageContext(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)@b@  {@b@    this(servletContext, request, response, null);@b@  }@b@@b@  public MockPageContext(ServletContext servletContext, HttpServletRequest request, HttpServletResponse response, ServletConfig servletConfig)@b@  {@b@    this.attributes = new LinkedHashMap();@b@@b@    this.servletContext = new MockServletContext();@b@    this.request = new MockHttpServletRequest(servletContext);@b@    this.response = new MockHttpServletResponse();@b@    this.servletConfig = new MockServletConfig(servletContext);@b@  }@b@@b@  public void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush)@b@  {@b@    throw new UnsupportedOperationException("Use appropriate constructor");@b@  }@b@@b@  public void release()@b@  {@b@  }@b@@b@  public void setAttribute(String name, Object value)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    if (value != null) {@b@      this.attributes.put(name, value);@b@    }@b@    else@b@      this.attributes.remove(name);@b@  }@b@@b@  public void setAttribute(String name, Object value, int scope)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    switch (scope)@b@    {@b@    case 1:@b@      setAttribute(name, value);@b@      break;@b@    case 2:@b@      this.request.setAttribute(name, value);@b@      break;@b@    case 3:@b@      this.request.getSession().setAttribute(name, value);@b@      break;@b@    case 4:@b@      this.servletContext.setAttribute(name, value);@b@      break;@b@    default:@b@      throw new IllegalArgumentException("Invalid scope: " + scope);@b@    }@b@  }@b@@b@  public Object getAttribute(String name)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    return this.attributes.get(name);@b@  }@b@@b@  public Object getAttribute(String name, int scope)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    switch (scope)@b@    {@b@    case 1:@b@      return getAttribute(name);@b@    case 2:@b@      return this.request.getAttribute(name);@b@    case 3:@b@      HttpSession session = this.request.getSession(false);@b@      return ((session != null) ? session.getAttribute(name) : null);@b@    case 4:@b@      return this.servletContext.getAttribute(name);@b@    }@b@    throw new IllegalArgumentException("Invalid scope: " + scope);@b@  }@b@@b@  public Object findAttribute(String name)@b@  {@b@    Object value = getAttribute(name);@b@    if (value == null) {@b@      value = getAttribute(name, 2);@b@      if (value == null) {@b@        value = getAttribute(name, 3);@b@        if (value == null)@b@          value = getAttribute(name, 4);@b@      }@b@    }@b@@b@    return value;@b@  }@b@@b@  public void removeAttribute(String name)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    removeAttribute(name, 1);@b@    removeAttribute(name, 2);@b@    removeAttribute(name, 3);@b@    removeAttribute(name, 4);@b@  }@b@@b@  public void removeAttribute(String name, int scope)@b@  {@b@    Assert.notNull(name, "Attribute name must not be null");@b@    switch (scope)@b@    {@b@    case 1:@b@      this.attributes.remove(name);@b@      break;@b@    case 2:@b@      this.request.removeAttribute(name);@b@      break;@b@    case 3:@b@      this.request.getSession().removeAttribute(name);@b@      break;@b@    case 4:@b@      this.servletContext.removeAttribute(name);@b@      break;@b@    default:@b@      throw new IllegalArgumentException("Invalid scope: " + scope);@b@    }@b@  }@b@@b@  public int getAttributesScope(String name)@b@  {@b@    if (getAttribute(name) != null)@b@      return 1;@b@@b@    if (getAttribute(name, 2) != null)@b@      return 2;@b@@b@    if (getAttribute(name, 3) != null)@b@      return 3;@b@@b@    if (getAttribute(name, 4) != null) {@b@      return 4;@b@    }@b@@b@    return 0;@b@  }@b@@b@  public Enumeration<String> getAttributeNames()@b@  {@b@    return Collections.enumeration(new LinkedHashSet(this.attributes.keySet()));@b@  }@b@@b@  public Enumeration<String> getAttributeNamesInScope(int scope)@b@  {@b@    switch (scope)@b@    {@b@    case 1:@b@      return getAttributeNames();@b@    case 2:@b@      return this.request.getAttributeNames();@b@    case 3:@b@      HttpSession session = this.request.getSession(false);@b@      return ((session != null) ? session.getAttributeNames() : null);@b@    case 4:@b@      return this.servletContext.getAttributeNames();@b@    }@b@    throw new IllegalArgumentException("Invalid scope: " + scope);@b@  }@b@@b@  public JspWriter getOut()@b@  {@b@    if (this.out == null)@b@      this.out = new MockJspWriter(this.response);@b@@b@    return this.out;@b@  }@b@@b@  @Deprecated@b@  public ExpressionEvaluator getExpressionEvaluator()@b@  {@b@    return new MockExpressionEvaluator(this);@b@  }@b@@b@  public ELContext getELContext()@b@  {@b@    return null;@b@  }@b@@b@  @Deprecated@b@  public VariableResolver getVariableResolver()@b@  {@b@    return null;@b@  }@b@@b@  public HttpSession getSession()@b@  {@b@    return this.request.getSession();@b@  }@b@@b@  public Object getPage()@b@  {@b@    return this;@b@  }@b@@b@  public ServletRequest getRequest()@b@  {@b@    return this.request;@b@  }@b@@b@  public ServletResponse getResponse()@b@  {@b@    return this.response;@b@  }@b@@b@  public Exception getException()@b@  {@b@    return null;@b@  }@b@@b@  public ServletConfig getServletConfig()@b@  {@b@    return this.servletConfig;@b@  }@b@@b@  public ServletContext getServletContext()@b@  {@b@    return this.servletContext;@b@  }@b@@b@  public void forward(String path) throws ServletException, IOException@b@  {@b@    this.request.getRequestDispatcher(path).forward(this.request, this.response);@b@  }@b@@b@  public void include(String path) throws ServletException, IOException@b@  {@b@    this.request.getRequestDispatcher(path).include(this.request, this.response);@b@  }@b@@b@  public void include(String path, boolean flush) throws ServletException, IOException@b@  {@b@    this.request.getRequestDispatcher(path).include(this.request, this.response);@b@    if (flush)@b@      this.response.flushBuffer();@b@  }@b@@b@  public byte[] getContentAsByteArray()@b@  {@b@    Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");@b@    return ((MockHttpServletResponse)this.response).getContentAsByteArray();@b@  }@b@@b@  public String getContentAsString() throws UnsupportedEncodingException {@b@    Assert.state(this.response instanceof MockHttpServletResponse, "MockHttpServletResponse required");@b@    return ((MockHttpServletResponse)this.response).getContentAsString();@b@  }@b@@b@  public void handlePageException(Exception ex) throws ServletException, IOException@b@  {@b@    throw new ServletException("Page exception", ex);@b@  }@b@@b@  public void handlePageException(Throwable ex) throws ServletException, IOException@b@  {@b@    throw new ServletException("Page exception", ex);@b@  }@b@}
package org.springframework.mock.web;@b@@b@import java.io.IOException;@b@import java.io.PrintWriter;@b@import java.io.Writer;@b@import javax.servlet.http.HttpServletResponse;@b@import javax.servlet.jsp.JspWriter;@b@@b@public class MockJspWriter extends JspWriter@b@{@b@  private final HttpServletResponse response;@b@  private PrintWriter targetWriter;@b@@b@  public MockJspWriter(HttpServletResponse response)@b@  {@b@    this(response, null);@b@  }@b@@b@  public MockJspWriter(Writer targetWriter)@b@  {@b@    this(null, targetWriter);@b@  }@b@@b@  public MockJspWriter(HttpServletResponse response, Writer targetWriter)@b@  {@b@    super(-1, true);@b@    this.response = new MockHttpServletResponse();@b@    if (targetWriter instanceof PrintWriter) {@b@      this.targetWriter = ((PrintWriter)targetWriter);@b@    }@b@    else if (targetWriter != null)@b@      this.targetWriter = new PrintWriter(targetWriter);@b@  }@b@@b@  protected PrintWriter getTargetWriter()@b@    throws IOException@b@  {@b@    if (this.targetWriter == null)@b@      this.targetWriter = this.response.getWriter();@b@@b@    return this.targetWriter;@b@  }@b@@b@  public void clear()@b@    throws IOException@b@  {@b@    if (this.response.isCommitted())@b@      throw new IOException("Response already committed");@b@@b@    this.response.resetBuffer();@b@  }@b@@b@  public void clearBuffer() throws IOException@b@  {@b@  }@b@@b@  public void flush() throws IOException@b@  {@b@    this.response.flushBuffer();@b@  }@b@@b@  public void close() throws IOException@b@  {@b@    flush();@b@  }@b@@b@  public int getRemaining()@b@  {@b@    return 2147483647;@b@  }@b@@b@  public void newLine() throws IOException@b@  {@b@    getTargetWriter().println();@b@  }@b@@b@  public void write(char[] value, int offset, int length) throws IOException@b@  {@b@    getTargetWriter().write(value, offset, length);@b@  }@b@@b@  public void print(boolean value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(char value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(char[] value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(double value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(float value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(int value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(long value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(Object value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void print(String value) throws IOException@b@  {@b@    getTargetWriter().print(value);@b@  }@b@@b@  public void println() throws IOException@b@  {@b@    getTargetWriter().println();@b@  }@b@@b@  public void println(boolean value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(char value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(char[] value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(double value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(float value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(int value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(long value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(Object value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@@b@  public void println(String value) throws IOException@b@  {@b@    getTargetWriter().println(value);@b@  }@b@}