[Jsptest-svn-commits] SF.net SVN: jsptest:[272] trunk/jsptest-jsp20/src
Status: Alpha
Brought to you by:
lkoskela
From: <lko...@us...> - 2012-05-04 10:56:41
|
Revision: 272 http://jsptest.svn.sourceforge.net/jsptest/?rev=272&view=rev Author: lkoskela Date: 2012-05-04 10:56:29 +0000 (Fri, 04 May 2012) Log Message: ----------- Add tests for the MockHttpServletRequest implementation (and fix some flaws along the way) Modified Paths: -------------- trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/JspImpl.java trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletRequest.java trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletResponse.java Added Paths: ----------- trunk/jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/mock/TestMockHttpServletRequest.java Modified: trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/JspImpl.java =================================================================== --- trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/JspImpl.java 2012-04-12 17:40:41 UTC (rev 271) +++ trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/JspImpl.java 2012-05-04 10:56:29 UTC (rev 272) @@ -1,6 +1,7 @@ package net.sf.jsptest.compiler.jsp20; import java.util.Map; + import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.http.HttpServlet; @@ -8,6 +9,7 @@ import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspFactory; + import net.sf.jsptest.compiler.api.Jsp; import net.sf.jsptest.compiler.api.JspExecution; import net.sf.jsptest.compiler.jsp20.mock.MockHttpServletRequest; @@ -18,6 +20,7 @@ import net.sf.jsptest.compiler.jsp20.mock.MockPageContext; import net.sf.jsptest.compiler.jsp20.mock.MockServletConfig; import net.sf.jsptest.compiler.jsp20.mock.MockServletContext; + import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; @@ -27,61 +30,85 @@ */ public class JspImpl implements Jsp { - private static final Log log = LogFactory.getLog(JspImpl.class); - private final Class servletClass; - private MockPageContext pageContext; + private static final Log log = LogFactory.getLog(JspImpl.class); + private final Class servletClass; + private MockPageContext pageContext; - public JspImpl(Class servletClass) { - this.servletClass = servletClass; - } + public JspImpl(Class servletClass) { + this.servletClass = servletClass; + } - public JspExecution request(String httpMethod, Map requestAttributes, Map sessionAttributes, Map requestParameters) { - ServletContext servletContext = new MockServletContext(); - ServletConfig servletConfig = new MockServletConfig(servletContext); - MockHttpSession httpSession = new MockHttpSession(); - httpSession.setAttributes(sessionAttributes); - MockHttpServletRequest request = new MockHttpServletRequest(); - request.setSession(httpSession); - request.setMethod(httpMethod); - request.setAttributes(requestAttributes); - request.setParameters(requestParameters); - MockHttpServletResponse response = new MockHttpServletResponse(); - MockJspWriter jspWriter = configureJspFactory(servletContext, request, httpSession); - initializeAndInvokeJsp(servletClass, servletConfig, request, response); - return createExecutionResult(jspWriter.getContents()); - } + public JspExecution request(String httpMethod, Map requestAttributes, + Map sessionAttributes, Map requestParameters) { + ServletContext servletContext = new MockServletContext(); + ServletConfig servletConfig = new MockServletConfig(servletContext); + MockHttpSession session = configureHttpSession(sessionAttributes); + MockHttpServletRequest request = configureHttpServletRequest( + httpMethod, requestAttributes, requestParameters, session); + MockHttpServletResponse response = new MockHttpServletResponse(); + MockJspWriter jspWriter = configureJspFactory(servletContext, request, + session); + initializeAndInvokeJsp(servletClass, servletConfig, request, response); + return createExecutionResult(jspWriter.getContents()); + } - protected MockJspWriter configureJspFactory(ServletContext httpContext, - HttpServletRequest httpRequest, HttpSession httpSession) { - pageContext = new MockPageContext(); - pageContext.setRequest(httpRequest); - pageContext.setServletContext(httpContext); - pageContext.setSession(httpSession); - MockJspWriter jspWriter = new MockJspWriter(); - pageContext.setJspWriter(jspWriter); - JspFactory.setDefaultFactory(new MockJspFactory(pageContext)); - return jspWriter; - } + private MockHttpSession configureHttpSession(Map sessionAttributes) { + MockHttpSession httpSession = new MockHttpSession(); + httpSession.setAttributes(sessionAttributes); + return httpSession; + } - protected void initializeAndInvokeJsp(Class jspClass, ServletConfig servletConfig, - HttpServletRequest request, HttpServletResponse response) { - try { - log.debug("Instantiating Servlet: " + jspClass.getName()); - HttpServlet servlet = (HttpServlet) jspClass.newInstance(); - log.debug("Initializing Servlet: " + jspClass.getName()); - servlet.init(servletConfig); - log.debug("Invoking Servlet: " + jspClass.getName()); - servlet.service(request, response); - if (pageContext.getException() != null) { - log.debug("An exception was stored into PageContext. Rethrowing it..."); - throw new RuntimeException(pageContext.getException()); - } - } catch (Exception e) { - throw new RuntimeException(e); - } - } + private MockHttpServletRequest configureHttpServletRequest( + String httpMethod, Map requestAttributes, Map requestParameters, + MockHttpSession session) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setSession(session); + request.setMethod(httpMethod); + request.setAttributes(requestAttributes); + request.setParameters(requestParameters); + return request; + } - protected JspExecution createExecutionResult(String output) { - return new JspExecutionImpl(output); - } + protected MockJspWriter configureJspFactory(ServletContext httpContext, + HttpServletRequest httpRequest, HttpSession httpSession) { + MockJspWriter jspWriter = new MockJspWriter(); + pageContext = configurePageContext(httpContext, httpRequest, + httpSession, jspWriter); + JspFactory.setDefaultFactory(new MockJspFactory(pageContext)); + return jspWriter; + } + + private MockPageContext configurePageContext(ServletContext httpContext, + HttpServletRequest httpRequest, HttpSession httpSession, + MockJspWriter jspWriter) { + MockPageContext pageContext = new MockPageContext(); + pageContext.setRequest(httpRequest); + pageContext.setServletContext(httpContext); + pageContext.setSession(httpSession); + pageContext.setJspWriter(jspWriter); + return pageContext; + } + + protected void initializeAndInvokeJsp(Class jspClass, + ServletConfig servletConfig, HttpServletRequest request, + HttpServletResponse response) { + try { + log.debug("Instantiating Servlet: " + jspClass.getName()); + HttpServlet servlet = (HttpServlet) jspClass.newInstance(); + log.debug("Initializing Servlet: " + jspClass.getName()); + servlet.init(servletConfig); + log.debug("Invoking Servlet: " + jspClass.getName()); + servlet.service(request, response); + if (pageContext.getException() != null) { + log.debug("An exception was stored into PageContext. Rethrowing it..."); + throw new RuntimeException(pageContext.getException()); + } + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + protected JspExecution createExecutionResult(String output) { + return new JspExecutionImpl(output); + } } Modified: trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletRequest.java =================================================================== --- trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletRequest.java 2012-04-12 17:40:41 UTC (rev 271) +++ trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletRequest.java 2012-05-04 10:56:29 UTC (rev 272) @@ -16,18 +16,27 @@ package net.sf.jsptest.compiler.jsp20.mock; import java.io.BufferedReader; +import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; +import java.io.InputStreamReader; +import java.net.MalformedURLException; +import java.net.URL; import java.security.Principal; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.ArrayList; import java.util.Arrays; +import java.util.Collection; +import java.util.Date; import java.util.Enumeration; import java.util.HashMap; import java.util.Iterator; +import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Vector; + import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; @@ -37,318 +46,564 @@ import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + /** * @author Lasse Koskela */ public class MockHttpServletRequest implements HttpServletRequest { - private Map headers = new HashMap(); - private Map parameters = new HashMap(); - private Map attributes = new HashMap(); - private MockHttpSession httpSession = null; - private byte[] body; - private String httpMethod; - private String characterEncoding; + private static final String LOCALHOST = "127.0.0.1"; + private static final Log log = LogFactory + .getLog(MockHttpServletRequest.class); + private Map headers = new HashMap(); + private Map parameters = new HashMap(); + private Map attributes = new HashMap(); + private MockHttpSession httpSession = null; + private byte[] body; + private String httpMethod; + private String characterEncoding; + private boolean hasAlreadyReadBody; + private String queryString; + private String scheme; + private String contextPath; + private int serverPort; + private String serverName; + private String servletPath; + private String requestURI; + static final SimpleDateFormat RFC2616 = new SimpleDateFormat( + "EEE, dd MMM yyyy HH:mm:ss z"); - public MockHttpServletRequest() { - this((MockHttpSession) null); - } + public MockHttpServletRequest() { + this((MockHttpSession) null); + } - public MockHttpServletRequest(MockHttpSession httpSession) { - setSession(httpSession); - } + public MockHttpServletRequest(byte[] body) { + this((MockHttpSession) null, body); + } - public MockHttpServletRequest(byte[] body) { - this.body = body; - characterEncoding = "UTF-8"; - this.headers.put("Content-type", "multipart/form-data; boundary=XXXBOUNDARYXXX"); - } + public MockHttpServletRequest(MockHttpSession httpSession) { + this(httpSession, null); + } - public String getAuthType() { - return null; - } + public MockHttpServletRequest(MockHttpSession httpSession, byte[] body) { + setSession(httpSession); + setScheme("http"); + setContextPath(""); + setServletPath(""); + setServerPort(8080); + setServerName("localhost"); + setCharacterEncoding("ISO-8859-1"); + setMethod("GET"); + setHeader("Content-type", + "multipart/form-data; boundary=XXXBOUNDARYXXX"); + setBody(body); + } - public Cookie[] getCookies() { - return new Cookie[0]; - } + public String getAuthType() { + return null; + } - public long getDateHeader(String s) { - try { - // TODO: use the HTTP date format pattern - return new SimpleDateFormat().parse((String) headers.get(s)).getTime(); - } catch (ParseException e) { - return 0; - } - } + public Cookie[] getCookies() { + return new Cookie[0]; + } - public String getHeader(String reference) { - return (String) headers.get(reference); - } + public long getDateHeader(String name) { + String value = (String) getHeader(name); + if (value == null) { + return -1; + } + try { + return RFC2616.parse(value).getTime(); + } catch (ParseException e) { + log.warn("Could not parse date header '" + name + "': " + value, e); + throw new IllegalArgumentException("Invalid date: " + value); + } + } - public Enumeration getHeaders(String s) { - return new Vector().elements(); - } + public void setHeader(String name, String value) { + String headerName = resolveHeaderName(name); + List values = (List) headers.get(headerName); + if (values == null) { + values = new ArrayList(); + } + values.add(value); + headers.put(headerName, values); + } - public Enumeration getHeaderNames() { - return new Vector(headers.keySet()).elements(); - } + public void setHeader(String name, Date value) { + setHeader(name, RFC2616.format(value)); + } - public int getIntHeader(String s) { - return Integer.parseInt(getHeader(s)); - } + public void setHeader(String name, int value) { + setHeader(name, String.valueOf(value)); + } - public void setMethod(String httpMethod) { - this.httpMethod = httpMethod; - } + public String getHeader(String name) { + List values = (List) headers.get(resolveHeaderName(name)); + if (values == null) { + return null; + } + return (String) values.get(0); + } - public String getMethod() { - return httpMethod; - } + private String resolveHeaderName(String name) { + Iterator headerNames = headers.keySet().iterator(); + while (headerNames.hasNext()) { + String headerName = (String) headerNames.next(); + if (headerName.equalsIgnoreCase(name)) { + return headerName; + } + } + return name; + } - public String getPathInfo() { - return "/"; - } + public Enumeration getHeaders(String name) { + Vector vector = new Vector(); + List values = (List) headers.get(resolveHeaderName(name)); + if (values != null) { + vector.addAll(values); + } + return vector.elements(); + } - public String getPathTranslated() { - return "/"; - } + public Enumeration getHeaderNames() { + return new Vector(headers.keySet()).elements(); + } - public String getContextPath() { - return "/"; - } + public int getIntHeader(String name) { + String value = getHeader(name); + if (value == null) { + return -1; + } + return Integer.parseInt(value); + } - public String getQueryString() { - return null; - } + public void setMethod(String httpMethod) { + this.httpMethod = httpMethod; + } - public String getRemoteUser() { - return null; - } + public String getMethod() { + return httpMethod; + } - public boolean isUserInRole(String s) { - return false; - } + public String getPathInfo() { + return "/"; + } - public Principal getUserPrincipal() { - return null; - } + public String getPathTranslated() { + return "/"; + } - public String getRequestedSessionId() { - return "JSPTESTSESSIONID"; - } + public String getContextPath() { + return contextPath; + } - public String getRequestURI() { - return "/"; - } + public void setContextPath(String path) { + if (requestURI != null && !requestURI.startsWith(path)) { + throw new IllegalArgumentException("Context path " + path + + " does not match the request URI " + requestURI); + } + this.contextPath = path; + } - public StringBuffer getRequestURL() { - return new StringBuffer("/"); - } + public String getQueryString() { + if (hasQueryString()) { + return queryString; + } + if (isGetRequest() && !parameters.isEmpty()) { + StringBuffer s = new StringBuffer(); + Iterator parameterNames = parameters.keySet().iterator(); + while (parameterNames.hasNext()) { + String name = (String) parameterNames.next(); + String[] values = (String[]) parameters.get(name); + for (int i = 0; i < values.length; i++) { + if (s.length() > 0) { + s.append("&"); + } + s.append(name).append("=").append(values[i]); + } + } + return s.toString(); + } + return null; + } - public String getServletPath() { - return "/"; - } + public void setQueryString(String queryStringWithoutLeadingQuestionMark) { + this.queryString = queryStringWithoutLeadingQuestionMark; + } - public HttpSession getSession(boolean flag) { - if (flag && httpSession == null) { - httpSession = new MockHttpSession(); - } - return httpSession; - } + public String getRemoteUser() { + return null; + } - public HttpSession getSession() { - return httpSession; - } + public boolean isUserInRole(String role) { + return false; + } - public boolean isRequestedSessionIdValid() { - return true; - } + public Principal getUserPrincipal() { + return null; + } - public boolean isRequestedSessionIdFromCookie() { - return true; - } + public String getRequestedSessionId() { + return "JSPTESTSESSIONID"; + } - public boolean isRequestedSessionIdFromURL() { - return false; - } + public void setRequestURI(String uri) { + if (contextPath != null && !uri.startsWith(contextPath)) { + throw new IllegalArgumentException("Request URI " + requestURI + + " does not match the Context path " + contextPath); + } + this.requestURI = uri; + } - public boolean isRequestedSessionIdFromUrl() { - return false; - } + public String getRequestURI() { + if (requestURI != null) { + return requestURI; + } + return getContextPath() + getServletPath(); + } - public Object getAttribute(String name) { - return attributes.get(name); - } + public void setRequestURL(String requestUrl) { + try { + URL url = new URL(requestUrl); + setScheme(url.getProtocol()); + setServerName(url.getHost()); + setServerPort(url.getPort()); + setRequestURI(url.getPath()); + } catch (MalformedURLException e) { + throw new RuntimeException(e); + } + } - public Enumeration getAttributeNames() { - return new Vector(attributes.keySet()).elements(); - } + public StringBuffer getRequestURL() { + StringBuffer url = new StringBuffer(); + url.append(getScheme()).append("://"); + url.append(getServerName()); + if (getServerPort() != 80) { + url.append(":").append(getServerPort()); + } + url.append(getRequestURI()); + return url; + } - public String getCharacterEncoding() { - return characterEncoding; - } + public void setServletPath(String path) { + this.servletPath = path; + } - public void setCharacterEncoding(String env) { - characterEncoding = env; - } + public String getServletPath() { + return servletPath; + } - public int getContentLength() { - return body.length; - } + public HttpSession getSession(boolean createNewSession) { + if (createNewSession && httpSession == null) { + httpSession = new MockHttpSession(); + } + return httpSession; + } - public String getContentType() { - return "multipart/form-data; boundary=xxx"; - } + public HttpSession getSession() { + return httpSession; + } - public ServletInputStream getInputStream() throws IOException { - return new MockServletInputStream(body); - } + public void setSession(MockHttpSession session) { + this.httpSession = session; + } - public String getParameter(String name) { - String values[] = (String[]) parameters.get(name); - if (values != null) { - return (values[0]); - } else { - return (null); - } - } + public boolean isRequestedSessionIdValid() { + return true; + } - public Map getParameterMap() { - return parameters; - } + public boolean isRequestedSessionIdFromCookie() { + return true; + } - public String getProtocol() { - return "http"; - } + public boolean isRequestedSessionIdFromURL() { + return isRequestedSessionIdFromUrl(); + } - public String getScheme() { - return "http://"; - } + public boolean isRequestedSessionIdFromUrl() { + return false; + } - public String getServerName() { - return "servername"; - } + public void setBody(byte[] body) { + this.body = body; + } - public int getServerPort() { - return 8080; - } + public String getCharacterEncoding() { + return characterEncoding; + } - public BufferedReader getReader() throws IOException { - return null; - } + public void setCharacterEncoding(String encoding) { + characterEncoding = encoding; + } - public String getRemoteAddr() { - return null; - } + public int getContentLength() { + return body.length; + } - public String getRemoteHost() { - return null; - } + public String getContentType() { + return "multipart/form-data; boundary=xxx"; + } - public void setAttributes(Map attributes) { - this.attributes.putAll(attributes); - } + public ServletInputStream getInputStream() throws IOException { + checkForEarlierAccessToRequestBody(); + return new MockServletInputStream(body); + } - public void setAttribute(String name, Object o) { - attributes.put(name, o); - } + public BufferedReader getReader() throws IOException { + checkForEarlierAccessToRequestBody(); + return new BufferedReader(new InputStreamReader( + new ByteArrayInputStream(body), characterEncoding)); + } - public void removeAttribute(String name) { - attributes.remove(name); - } + private void checkForEarlierAccessToRequestBody() throws IOException { + if (hasAlreadyReadBody) { + throw new IOException("You've read the request body already!"); + } + hasAlreadyReadBody = true; + } - public Locale getLocale() { - return Locale.getDefault(); - } + public String getProtocol() { + return "HTTP/1.1"; + } - public Enumeration getLocales() { - return new Vector(Arrays.asList(Locale.getAvailableLocales())).elements(); - } + public String getScheme() { + return scheme; + } - public boolean isSecure() { - return false; - } + public void setScheme(String scheme) { + this.scheme = scheme; + } - public RequestDispatcher getRequestDispatcher(String s) { - return new RequestDispatcher() { + public boolean isSecure() { + return getProtocol().equals("https"); + } - public void forward(ServletRequest request, ServletResponse response) - throws ServletException, IOException { - } + public void setServerName(String name) { + this.serverName = name; + } - public void include(ServletRequest request, ServletResponse response) - throws ServletException, IOException { - } - }; - } + public String getServerName() { + return serverName; + } - public String getRealPath(String s) { - File tmpDir = new File(System.getProperty("java.io.tmpdir")); - File jsptestTmpDir = new File(tmpDir, "jsptest"); - return new File(jsptestTmpDir, s).getAbsolutePath(); - } + public void setServerPort(int port) { + this.serverPort = port; + } - public int getRemotePort() { - return 11111; - } + public int getServerPort() { + return serverPort; + } - public String getLocalName() { - return null; - } + public String getRemoteAddr() { + return LOCALHOST; + } - public String getLocalAddr() { - return null; - } + public String getRemoteHost() { + return "localhost"; + } - public int getLocalPort() { - return 22222; - } + public int getRemotePort() { + return 11111; + } - public void addParameter(String name, String values[]) { - parameters.put(name, values); - } + public int getLocalPort() { + return 22222; + } - public String toString() { - StringBuffer buffer = new StringBuffer(); - buffer.append(getClass().getName()).append("{"); - Enumeration enumeration = getParameterNames(); - while (enumeration.hasMoreElements()) { - String key = (String) enumeration.nextElement(); - String[] values = getParameterValues(key); - buffer.append("parameter:"); - buffer.append(key); - buffer.append("=["); - for (int i = 0; i < values.length; i++) { - String value = values[i]; - buffer.append(value); - if (i < values.length - 1) { - buffer.append(","); - } - } - buffer.append("]\n"); - } - buffer.append("}"); - return buffer.toString(); - } + public String getLocalName() { + return LOCALHOST; + } - public Enumeration getParameterNames() { - return new Vector(parameters.keySet()).elements(); - } + public String getLocalAddr() { + return LOCALHOST; + } - public String[] getParameterValues(String name) { - return (String[]) parameters.get(name); - } - - public void setParameters(Map requestParameters) { - Iterator parameterNames = requestParameters.keySet().iterator(); - while (parameterNames.hasNext()) { - String name = (String) parameterNames.next(); - String[] values = (String[]) requestParameters.get(name); - parameters.put(name, values); - } - } + public Object getAttribute(String name) { + return attributes.get(name); + } - public void setSession(MockHttpSession session) { - this.httpSession = session; - } + public Enumeration getAttributeNames() { + return new Vector(attributes.keySet()).elements(); + } + + public void setAttributes(Map attributes) { + this.attributes.putAll(attributes); + } + + public void setAttribute(String name, Object value) { + attributes.put(name, value); + } + + public void removeAttribute(String name) { + attributes.remove(name); + } + + public Enumeration getParameterNames() { + return new Vector(getParameterMap().keySet()).elements(); + } + + public Map getParameterMap() { + if (isGetRequest() && hasQueryString()) { + return getQueryStringParameterMap(); + } + if (isPostRequest() && hasQueryString()) { + return join(parameters, getQueryStringParameterMap()); + } + return new HashMap(parameters); + } + + public String[] getParameterValues(String name) { + return (String[]) getParameterMap().get(name); + } + + public String getParameter(String name) { + String values[] = (String[]) getParameterMap().get(name); + if (values != null) { + return values[0]; + } + return null; + } + + public void addParameter(String name, String[] values) { + String[] oldValues = (String[]) parameters.get(name); + if (oldValues != null) { + values = join(oldValues, values); + } + parameters.put(name, values); + } + + public void addParameter(String name, String value) { + addParameter(name, new String[] { value }); + } + + public void setParameters(Map requestParameters) { + Iterator parameterNames = requestParameters.keySet().iterator(); + while (parameterNames.hasNext()) { + String name = (String) parameterNames.next(); + String[] values = (String[]) requestParameters.get(name); + parameters.put(name, values); + } + } + + public void setParameter(String name, String value) { + setParameter(name, new String[] { value }); + } + + public void setParameter(String name, String[] values) { + parameters.put(name, values); + } + + public Locale getLocale() { + return Locale.getDefault(); + } + + public Enumeration getLocales() { + List locales = Arrays.asList(Locale.getAvailableLocales()); + return new Vector(locales).elements(); + } + + public RequestDispatcher getRequestDispatcher(String path) { + return new RequestDispatcher() { + + public void forward(ServletRequest request, ServletResponse response) + throws ServletException, IOException { + } + + public void include(ServletRequest request, ServletResponse response) + throws ServletException, IOException { + } + }; + } + + public String getRealPath(String path) { + File tmpDir = new File(System.getProperty("java.io.tmpdir")); + File jsptestTmpDir = new File(tmpDir, "jsptest"); + return new File(jsptestTmpDir, path).getAbsolutePath(); + } + + public String toString() { + StringBuffer buffer = new StringBuffer(); + buffer.append(getClass().getName()).append("{"); + Enumeration enumeration = getParameterNames(); + while (enumeration.hasMoreElements()) { + String key = (String) enumeration.nextElement(); + String[] values = getParameterValues(key); + buffer.append("parameter:"); + buffer.append(key); + buffer.append("=["); + for (int i = 0; i < values.length; i++) { + buffer.append(values[i]); + if (i < values.length - 1) { + buffer.append(","); + } + } + buffer.append("]\n"); + } + buffer.append("}"); + return buffer.toString(); + } + + private String[] join(String[] array, String[] anotherArray) { + List joined = new ArrayList(); + if (array != null) { + joined.addAll(Arrays.asList(array)); + } + if (anotherArray != null) { + joined.addAll(Arrays.asList(anotherArray)); + } + return (String[]) joined.toArray(new String[joined.size()]); + } + + private Map join(Map map, Map anotherMap) { + Map joined = new HashMap(); + Collection keys = join(map.keySet(), anotherMap.keySet()); + Iterator allKeys = keys.iterator(); + while (allKeys.hasNext()) { + String key = (String) allKeys.next(); + String[] values1 = (String[]) map.get(key); + String[] values2 = (String[]) anotherMap.get(key); + joined.put(key, join(values1, values2)); + } + return joined; + } + + private Collection join(Collection collection, Collection anotherCollection) { + Collection joined = new ArrayList(); + if (collection != null) { + joined.addAll(collection); + } + if (anotherCollection != null) { + joined.addAll(anotherCollection); + } + return joined; + } + + private Map getQueryStringParameterMap() { + Map parameters = new HashMap(); + String[] pairs = queryString.split("&"); + for (int i = 0; i < pairs.length; i++) { + String[] nameAndValue = pairs[i].split("=", 2); + String name = nameAndValue[0]; + String value = nameAndValue[1]; + String[] existingValues = (String[]) parameters.get(name); + String[] newValues = join(existingValues, new String[] { value }); + parameters.put(name, newValues); + } + return parameters; + } + + private boolean hasQueryString() { + return queryString != null; + } + + private boolean isGetRequest() { + return "GET".equals(getMethod()); + } + + private boolean isPostRequest() { + return "POST".equals(getMethod()); + } } Modified: trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletResponse.java =================================================================== --- trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletResponse.java 2012-04-12 17:40:41 UTC (rev 271) +++ trunk/jsptest-jsp20/src/main/java/net/sf/jsptest/compiler/jsp20/mock/MockHttpServletResponse.java 2012-05-04 10:56:29 UTC (rev 272) @@ -33,142 +33,153 @@ */ public class MockHttpServletResponse implements HttpServletResponse { - private ServletOutputStream servletOutputStream; - private String description; - private PrintWriter writer; + private String characterEncoding; + private ServletOutputStream servletOutputStream; + private String description; + private PrintWriter writer; + private Locale locale; + private String contentType; + private int bufferSize; - public MockHttpServletResponse() { - this(new ByteArrayOutputStream()); - description = "(in-memory)"; - } + public MockHttpServletResponse() { + this(new ByteArrayOutputStream()); + description = "(in-memory)"; + } - public MockHttpServletResponse(File output) throws FileNotFoundException { - this(new FileOutputStream(output)); - description = "(output file: " + output.getAbsolutePath() + ")"; - } + public MockHttpServletResponse(File output) throws FileNotFoundException { + this(new FileOutputStream(output)); + description = "(output file: " + output.getAbsolutePath() + ")"; + } - private MockHttpServletResponse(final OutputStream output) { - this.servletOutputStream = new JspTestServletOutputStream(output); - writer = new PrintWriter(servletOutputStream) { - }; - } + private MockHttpServletResponse(final OutputStream output) { + this.servletOutputStream = new JspTestServletOutputStream(output); + writer = new PrintWriter(servletOutputStream) { + }; + this.bufferSize = 0; + this.locale = Locale.getDefault(); + this.characterEncoding = "ISO-8859-1"; + } - public String toString() { - return super.toString() + " " + description; - } + public String toString() { + return super.toString() + " " + description; + } - public void addCookie(Cookie cookie) { - } + public void addCookie(Cookie cookie) { + } - public void addDateHeader(String s, long l) { - } + public void setDateHeader(String name, long timestamp) { + } - public void addHeader(String s, String s1) { - } + public void setHeader(String name, String value) { + } - public void addIntHeader(String s, int i) { - } + public void setIntHeader(String name, int value) { + } - public boolean containsHeader(String s) { - return false; - } + public void addDateHeader(String name, long timestamp) { + } - public String encodeRedirectURL(String s) { - return null; - } + public void addHeader(String name, String value) { + } - /** @deprecated */ - public String encodeRedirectUrl(String s) { - return null; - } + public void addIntHeader(String name, int value) { + } - public String encodeURL(String s) { - return s; - } + public boolean containsHeader(String name) { + return false; + } - /** @deprecated */ - public String encodeUrl(String s) { - return s; - } + public String encodeRedirectURL(String url) { + return url; + } - public void flushBuffer() throws IOException { - getOutputStream().flush(); - } + /** @deprecated */ + public String encodeRedirectUrl(String url) { + return url; + } - public int getBufferSize() { - return 0; - } + public String encodeURL(String url) { + return url; + } - public String getCharacterEncoding() { - return null; - } + /** @deprecated */ + public String encodeUrl(String url) { + return url; + } - public Locale getLocale() { - return null; - } + public void reset() { + } - public ServletOutputStream getOutputStream() throws IOException { - return servletOutputStream; - } + public void resetBuffer() { + } - public PrintWriter getWriter() throws IOException { - return writer; - } + public void setBufferSize(int size) { + this.bufferSize = size; + } - public boolean isCommitted() { - return false; - } + public int getBufferSize() { + return bufferSize; + } - public void reset() { - } + public void flushBuffer() throws IOException { + getOutputStream().flush(); + } - public void resetBuffer() { - } + public String getCharacterEncoding() { + return characterEncoding; + } - public void sendError(int i) throws IOException { - throw new RuntimeException("Not implemented"); - } + public void setCharacterEncoding(String reference) { + } - public void sendError(int i, String s) throws IOException { - throw new RuntimeException("Not implemented"); - } + public Locale getLocale() { + return locale; + } - public void sendRedirect(String s) throws IOException { - throw new RuntimeException("Not implemented"); - } + public void setLocale(Locale locale) { + this.locale = locale; + } - public void setBufferSize(int i) { - } + public ServletOutputStream getOutputStream() throws IOException { + return servletOutputStream; + } - public void setContentLength(int i) { - } + public PrintWriter getWriter() throws IOException { + return writer; + } - public void setContentType(String s) { - } + public boolean isCommitted() { + return false; + } - public void setDateHeader(String s, long l) { - } + /** @deprecated */ + public void setStatus(int statusCode) { + } - public void setHeader(String s, String s1) { - } + public void setStatus(int statusCode, String description) { + } - public void setIntHeader(String s, int i) { - } + public void sendError(int statusCode) throws IOException { + throw new RuntimeException("Not implemented"); + } - public void setLocale(Locale locale) { - } + public void sendError(int statusCode, String description) + throws IOException { + throw new RuntimeException("Not implemented"); + } - /** @deprecated */ - public void setStatus(int i) { - } + public void sendRedirect(String location) throws IOException { + throw new RuntimeException("Not implemented"); + } - public void setStatus(int i, String s) { - } + public void setContentLength(int contentLength) { + } - public String getContentType() { - return null; - } + public void setContentType(String mimeType) { + this.contentType = mimeType; + } - public void setCharacterEncoding(String reference) { - } + public String getContentType() { + return contentType; + } } Added: trunk/jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/mock/TestMockHttpServletRequest.java =================================================================== --- trunk/jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/mock/TestMockHttpServletRequest.java (rev 0) +++ trunk/jsptest-jsp20/src/test/java/net/sf/jsptest/compiler/jsp20/mock/TestMockHttpServletRequest.java 2012-05-04 10:56:29 UTC (rev 272) @@ -0,0 +1,331 @@ +package net.sf.jsptest.compiler.jsp20.mock; + +import java.io.BufferedReader; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.Reader; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Date; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.List; + +import junit.framework.TestCase; + +public class TestMockHttpServletRequest extends TestCase { + + private MockHttpServletRequest get; + private MockHttpServletRequest post; + private byte[] body; + + protected void setUp() throws Exception { + body = "body".getBytes(); + get = new MockHttpServletRequest(); + post = new MockHttpServletRequest(body); + post.setMethod("POST"); + } + + public void testCharacterEncodingCanBeConfigured() throws Exception { + assertEquals("ISO-8859-1", get.getCharacterEncoding()); + get.setCharacterEncoding("UTF-8"); + assertEquals("UTF-8", get.getCharacterEncoding()); + } + + public void testReadingRequestBodyAsInputStream() throws Exception { + assertEquals(new String(body), asString(post.getInputStream())); + } + + public void testReadingRequestBodyThroughBufferedReader() throws Exception { + assertEquals(new String(body), asString(post.getReader())); + } + + public void testCannotReadBodyTwiceThroughInputStream() throws Exception { + post.getInputStream(); + try { + post.getInputStream(); + fail("shouldn't let us access the InputStream twice!"); + } catch (IOException expected) { + } + } + + public void testCannotReadBodyTwiceThroughReader() throws Exception { + post.getReader(); + try { + post.getReader(); + fail("shouldn't let us access the BufferedReader twice!"); + } catch (IOException expected) { + } + } + + public void testCannotReadBodyTwiceWithDifferentMethods() throws Exception { + try { + post.getReader(); + post.getInputStream(); + fail("shouldn't let us access the BufferedReader AND the InputStream!"); + } catch (IOException expected) { + } + try { + post.getInputStream(); + post.getReader(); + fail("shouldn't let us access the InputStreamAND the BufferedReader !"); + } catch (IOException expected) { + } + } + + // TODO: test handling body and its length + + public void testSettingIndividualHeader() throws Exception { + get.setHeader("X-Vibe", "Cool"); + assertEquals("Cool", get.getHeader("X-Vibe")); + assertEquals("Cool", get.getHeader("x-VibE")); + assertEquals(asList(new String[] { "Cool" }), + collect(get.getHeaders("x-vibe"))); + assertTrue(collect(get.getHeaderNames()).contains("X-Vibe")); + assertFalse(collect(get.getHeaderNames()).contains("x-ViBe")); + } + + public void testSettingMultipleValuesForHeader() throws Exception { + get.setHeader("X-VIBE", "Uppercase"); + get.setHeader("X-VIBE", "Another Uppercase"); + get.setHeader("x-vibe", "Lowercase"); + assertEquals("Uppercase", get.getHeader("X-vIbE")); + assertEquals(asList(new String[] { "Uppercase", "Another Uppercase", + "Lowercase" }), collect(get.getHeaders("x-VibE"))); + assertTrue(collect(get.getHeaderNames()).contains("X-VIBE")); + assertFalse(collect(get.getHeaderNames()).contains("x-vibe")); + } + + public void testDateHeader() throws Exception { + Date date = MockHttpServletRequest.RFC2616 + .parse("Fri, 04 May 2012 06:41:23 GMT"); + get.setHeader("X-Date1", date); + assertEquals(date.getTime(), get.getDateHeader("X-Date1")); + get.setHeader("X-Date2", MockHttpServletRequest.RFC2616.format(date)); + assertEquals(date.getTime(), get.getDateHeader("X-Date2")); + } + + public void testIntHeader() throws Exception { + get.setHeader("X-NotANumber", "NotANumber"); + get.setHeader("X-Number", 123); + get.setHeader("X-Number", "456"); + assertEquals(123, get.getIntHeader("X-Number")); + assertEquals(-1, get.getIntHeader("X-No-Such-Header")); + try { + get.getIntHeader("X-NotANumber"); + fail("Using getIntHeader() on NaN header value should yield an exception"); + } catch (NumberFormatException expected) { + } + } + + public void testAttributes() throws Exception { + post.setAttribute("name", "value"); + post.setAttribute("over", "whatever"); + post.setAttributes(new HashMap() { + { + put("over", "written"); + } + }); + assertEquals("value", post.getAttribute("name")); + assertEquals("written", post.getAttribute("over")); + assertTrue(collect(post.getAttributeNames()).contains("name")); + assertTrue(collect(post.getAttributeNames()).contains("over")); + } + + public void testAddingValueForSameParameterMultipleTimes() { + post.addParameter("name", "value1"); + post.addParameter("name", "value2"); + assertTrue(collect(post.getParameterNames()).contains("name")); + List parameterValues = asList(post.getParameterValues("name")); + assertTrue(parameterValues.contains("value1")); + assertTrue(parameterValues.contains("value2")); + } + + public void testSettingParametersOverwritesExistingValues() + throws Exception { + post.addParameter("name", "original"); + post.setParameters(new HashMap() { + { + put("name", new String[] { "new value" }); + } + }); + assertEquals("new value", post.getParameter("name")); + assertFalse(asList(post.getParameterValues("name")) + .contains("original")); + } + + public void testGetQueryStringReturnsNullWhenNoQueryParametersWereSet() + throws Exception { + assertNull(get.getQueryString()); + assertNull(post.getQueryString()); + } + + public void testQueryStringShouldBeTheOneThatWasSet() throws Exception { + get.setQueryString("foo=bar&xyz=123"); + assertEquals("foo=bar&xyz=123", get.getQueryString()); + } + + public void testQueryStringShouldMatchParametersAddedToGetRequest() + throws Exception { + get.addParameter("xyz", new String[] { "456", "123" }); + get.addParameter("foo", "bar"); + assertEquals("foo=bar&xyz=456&xyz=123", get.getQueryString()); + } + + public void testParametersShouldMatchTheQueryStringSetToGetRequest() + throws Exception { + get.setQueryString("foo=bar&xyz=456&xyz=123"); + assertEquals("bar", get.getParameter("foo")); + assertEquals(asList(new String[] { "456", "123" }), + asList(get.getParameterValues("xyz"))); + assertEquals(asList(new String[] { "foo", "xyz" }), + collect(get.getParameterNames())); + } + + public void testPostRequestCouldHaveBothQueryStringParametersAndBodyParameters() + throws Exception { + post.setQueryString("param=querystring"); + post.addParameter("param", "added"); + assertEquals(asList(new String[] { "added", "querystring" }), + asList(post.getParameterValues("param"))); + } + + public void testGetRealPathPointsUnderSystemTempDir() throws Exception { + String realPath = get.getRealPath("/admin/index.jsp"); + assertTrue(realPath.endsWith("/admin/index.jsp")); + assertTrue(realPath.startsWith(System.getProperty("java.io.tmpdir"))); + } + + public void testGetRequestURLIsConsistentWithSpecificQueryMethods() + throws Exception { + get.setScheme("https"); + get.setContextPath("/contextpath"); + get.setServerPort(1234); + get.setServerName("servername"); + get.setServletPath("/servletpath"); + get.setQueryString("query=string"); + + assertEquals("/contextpath/servletpath", get.getRequestURI()); + assertEquals("https://servername:1234/contextpath/servletpath", get + .getRequestURL().toString()); + } + + public void testRequestURICanBeSet() throws Exception { + get.setRequestURI("/path/to/page.jsp"); + assertEquals("/path/to/page.jsp", get.getRequestURI()); + assertEquals("", get.getContextPath()); + assertEquals("", get.getServletPath()); + } + + public void testSettingRequestURIContextPathAndServletPaths() + throws Exception { + get.setRequestURI("/path/to/page.jsp"); + get.setContextPath("/path"); + get.setServletPath("/to"); + assertEquals("/path/to/page.jsp", get.getRequestURI()); + assertEquals("/path", get.getContextPath()); + assertEquals("/to", get.getServletPath()); + } + + public void testRequestURIMustMatchPreviouslySetContextPath() + throws Exception { + post.setContextPath("/context"); + try { + post.setRequestURI("/differentContext/page.jsp"); + fail("Request URI must match the context path that was set."); + } catch (IllegalArgumentException expected) { + } + } + + public void testContextPathMustMatchPreviouslySetRequestURI() + throws Exception { + get.setRequestURI("/path/to/page.jsp"); + try { + get.setContextPath("/differentPath"); + fail("Context path must match the request URI that was set."); + } catch (IllegalArgumentException expected) { + } + } + + public void testRequestURLCanBeSet() throws Exception { + get.setRequestURL("http://server:99/path/to/page.jsp"); + assertEquals("http://server:99/path/to/page.jsp", get.getRequestURL() + .toString()); + assertEquals("", get.getContextPath()); + assertEquals("", get.getServletPath()); + } + + public void testSettingSpecificPartsAfterSettingTheFullRequestURL() + throws Exception { + get.setRequestURL("http://whatever/context/path"); + get.setServerName("something.el.se"); + get.setServerPort(8000); + get.setContextPath("/context"); + assertEquals("http://something.el.se:8000/context/path", get + .getRequestURL().toString()); + assertEquals("something.el.se", get.getServerName()); + assertEquals(8000, get.getServerPort()); + assertEquals("/context", get.getContextPath()); + } + + private String asString(InputStream stream) + throws UnsupportedEncodingException { + return asString(stream, "UTF-8"); + } + + private String asString(InputStream stream, String charset) + throws UnsupportedEncodingException { + return new String(contentOf(stream, charset), charset); + } + + private String asString(BufferedReader reader) + throws UnsupportedEncodingException { + return asString(reader, "UTF-8"); + } + + private String asString(BufferedReader reader, String charset) + throws UnsupportedEncodingException { + return new String(contentOf(reader), charset); + } + + private byte[] contentOf(InputStream stream, String charset) { + try { + return contentOf(new InputStreamReader(stream, charset)); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } + + private byte[] contentOf(Reader reader) { + try { + ByteArrayOutputStream buffer = new ByteArrayOutputStream(); + int b = -1; + while ((b = reader.read()) != -1) { + buffer.write(b); + } + return buffer.toByteArray(); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + private Collection collect(Enumeration enumeration) { + Collection list = new ArrayList(); + while (enumeration.hasMoreElements()) { + list.add(enumeration.nextElement()); + } + return list; + } + + private List asList(String string) { + return asList(new String[] { string }); + } + + private List asList(String[] array) { + return Arrays.asList(array); + } +} This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site. |