KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > springframework > mock > web > MockHttpServletResponse


1 /*
2  * Copyright 2002-2007 the original author or authors.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16
17 package org.springframework.mock.web;
18
19 import java.io.ByteArrayOutputStream JavaDoc;
20 import java.io.IOException JavaDoc;
21 import java.io.OutputStreamWriter JavaDoc;
22 import java.io.PrintWriter JavaDoc;
23 import java.io.UnsupportedEncodingException JavaDoc;
24 import java.io.Writer JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Collections JavaDoc;
27 import java.util.HashMap JavaDoc;
28 import java.util.Iterator JavaDoc;
29 import java.util.List JavaDoc;
30 import java.util.Locale JavaDoc;
31 import java.util.Map JavaDoc;
32 import java.util.Set JavaDoc;
33
34 import javax.servlet.ServletOutputStream JavaDoc;
35 import javax.servlet.http.Cookie JavaDoc;
36 import javax.servlet.http.HttpServletResponse JavaDoc;
37
38 import org.springframework.util.Assert;
39 import org.springframework.web.util.WebUtils;
40
41 /**
42  * Mock implementation of the {@link javax.servlet.http.HttpServletResponse}
43  * interface. Supports the Servlet 2.4 API level.
44  *
45  * <p>Used for testing the web framework; also useful for testing
46  * application controllers.
47  *
48  * @author Juergen Hoeller
49  * @author Rod Johnson
50  * @since 1.0.2
51  */

52 public class MockHttpServletResponse implements HttpServletResponse JavaDoc {
53
54     public static final int DEFAULT_SERVER_PORT = 80;
55
56     private static final String JavaDoc CHARSET_PREFIX = "charset=";
57
58
59     //---------------------------------------------------------------------
60
// ServletResponse properties
61
//---------------------------------------------------------------------
62

63     private boolean outputStreamAccessAllowed = true;
64
65     private boolean writerAccessAllowed = true;
66
67     private String JavaDoc characterEncoding = WebUtils.DEFAULT_CHARACTER_ENCODING;
68
69     private final ByteArrayOutputStream JavaDoc content = new ByteArrayOutputStream JavaDoc();
70
71     private final DelegatingServletOutputStream outputStream = new DelegatingServletOutputStream(this.content);
72
73     private PrintWriter JavaDoc writer;
74
75     private int contentLength = 0;
76
77     private String JavaDoc contentType;
78
79     private int bufferSize = 4096;
80
81     private boolean committed;
82
83     private Locale JavaDoc locale = Locale.getDefault();
84
85
86     //---------------------------------------------------------------------
87
// HttpServletResponse properties
88
//---------------------------------------------------------------------
89

90     private final List JavaDoc cookies = new ArrayList JavaDoc();
91
92     /**
93      * The key is the lowercase header name; the value is a {@link HeaderValueHolder} object.
94      */

95     private final Map JavaDoc headers = new HashMap JavaDoc();
96
97     private int status = HttpServletResponse.SC_OK;
98
99     private String JavaDoc errorMessage;
100
101     private String JavaDoc redirectedUrl;
102
103     private String JavaDoc forwardedUrl;
104
105     private String JavaDoc includedUrl;
106
107
108     //---------------------------------------------------------------------
109
// ServletResponse interface
110
//---------------------------------------------------------------------
111

112     /**
113      * Set whether {@link #getOutputStream()} access is allowed.
114      * <p>Default is <code>true</code>.
115      */

116     public void setOutputStreamAccessAllowed(boolean outputStreamAccessAllowed) {
117         this.outputStreamAccessAllowed = outputStreamAccessAllowed;
118     }
119
120     /**
121      * Return whether {@link #getOutputStream()} access is allowed.
122      */

123     public boolean isOutputStreamAccessAllowed() {
124         return this.outputStreamAccessAllowed;
125     }
126
127     /**
128      * Set whether {@link #getWriter()} access is allowed.
129      * <p>Default is <code>true</code>.
130      */

131     public void setWriterAccessAllowed(boolean writerAccessAllowed) {
132         this.writerAccessAllowed = writerAccessAllowed;
133     }
134
135     /**
136      * Return whether {@link #getOutputStream()} access is allowed.
137      */

138     public boolean isWriterAccessAllowed() {
139         return this.writerAccessAllowed;
140     }
141
142     public void setCharacterEncoding(String JavaDoc characterEncoding) {
143         this.characterEncoding = characterEncoding;
144     }
145
146     public String JavaDoc getCharacterEncoding() {
147         return this.characterEncoding;
148     }
149
150     public ServletOutputStream JavaDoc getOutputStream() {
151         if (!this.outputStreamAccessAllowed) {
152             throw new IllegalStateException JavaDoc("OutputStream access not allowed");
153         }
154         return this.outputStream;
155     }
156
157     public PrintWriter JavaDoc getWriter() throws UnsupportedEncodingException JavaDoc {
158         if (!this.writerAccessAllowed) {
159             throw new IllegalStateException JavaDoc("Writer access not allowed");
160         }
161         if (this.writer == null) {
162             Writer JavaDoc targetWriter = (this.characterEncoding != null ?
163                     new OutputStreamWriter JavaDoc(this.content, this.characterEncoding) : new OutputStreamWriter JavaDoc(this.content));
164             this.writer = new PrintWriter JavaDoc(targetWriter);
165         }
166         return this.writer;
167     }
168
169     public byte[] getContentAsByteArray() {
170         flushBuffer();
171         return this.content.toByteArray();
172     }
173
174     public String JavaDoc getContentAsString() throws UnsupportedEncodingException JavaDoc {
175         flushBuffer();
176         return (this.characterEncoding != null) ?
177                 this.content.toString(this.characterEncoding) : this.content.toString();
178     }
179
180     public void setContentLength(int contentLength) {
181         this.contentLength = contentLength;
182     }
183
184     public int getContentLength() {
185         return this.contentLength;
186     }
187
188     public void setContentType(String JavaDoc contentType) {
189         this.contentType = contentType;
190         if (contentType != null) {
191             int charsetIndex = contentType.toLowerCase().indexOf(CHARSET_PREFIX);
192             if (charsetIndex != -1) {
193                 String JavaDoc encoding = contentType.substring(charsetIndex + CHARSET_PREFIX.length());
194                 setCharacterEncoding(encoding);
195             }
196         }
197     }
198
199     public String JavaDoc getContentType() {
200         return this.contentType;
201     }
202
203     public void setBufferSize(int bufferSize) {
204         this.bufferSize = bufferSize;
205     }
206
207     public int getBufferSize() {
208         return this.bufferSize;
209     }
210
211     public void flushBuffer() {
212         if (this.writer != null) {
213             this.writer.flush();
214         }
215         if (this.outputStream != null) {
216             try {
217                 this.outputStream.flush();
218             }
219             catch (IOException JavaDoc ex) {
220                 throw new IllegalStateException JavaDoc("Could not flush OutputStream: " + ex.getMessage());
221             }
222         }
223         this.committed = true;
224     }
225
226     public void resetBuffer() {
227         if (this.committed) {
228             throw new IllegalStateException JavaDoc("Cannot reset buffer - response is already committed");
229         }
230         this.content.reset();
231     }
232
233     public void setCommitted(boolean committed) {
234         this.committed = committed;
235     }
236
237     public boolean isCommitted() {
238         return this.committed;
239     }
240
241     public void reset() {
242         resetBuffer();
243         this.characterEncoding = null;
244         this.contentLength = 0;
245         this.contentType = null;
246         this.locale = null;
247         this.cookies.clear();
248         this.headers.clear();
249         this.status = HttpServletResponse.SC_OK;
250         this.errorMessage = null;
251     }
252
253     public void setLocale(Locale JavaDoc locale) {
254         this.locale = locale;
255     }
256
257     public Locale JavaDoc getLocale() {
258         return this.locale;
259     }
260
261
262     //---------------------------------------------------------------------
263
// HttpServletResponse interface
264
//---------------------------------------------------------------------
265

266     public void addCookie(Cookie JavaDoc cookie) {
267         Assert.notNull(cookie, "Cookie must not be null");
268         this.cookies.add(cookie);
269     }
270
271     public Cookie JavaDoc[] getCookies() {
272         return (Cookie JavaDoc[]) this.cookies.toArray(new Cookie JavaDoc[this.cookies.size()]);
273     }
274
275     public Cookie JavaDoc getCookie(String JavaDoc name) {
276         Assert.notNull(name, "Cookie name must not be null");
277         for (Iterator JavaDoc it = this.cookies.iterator(); it.hasNext();) {
278             Cookie JavaDoc cookie = (Cookie JavaDoc) it.next();
279             if (name.equals(cookie.getName())) {
280                 return cookie;
281             }
282         }
283         return null;
284     }
285
286     public boolean containsHeader(String JavaDoc name) {
287         return (HeaderValueHolder.getByName(this.headers, name) != null);
288     }
289
290     /**
291      * Return the names of all specified headers as a Set of Strings.
292      * @return the <code>Set</code> of header name <code>Strings</code>, or an empty <code>Set</code> if none
293      */

294     public Set JavaDoc getHeaderNames() {
295         return this.headers.keySet();
296     }
297
298     /**
299      * Return the primary value for the given header, if any.
300      * <p>Will return the first value in case of multiple values.
301      * @param name the name of the header
302      * @return the associated header value, or <code>null<code> if none
303      */

304     public Object JavaDoc getHeader(String JavaDoc name) {
305         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
306         return (header != null ? header.getValue() : null);
307     }
308
309     /**
310      * Return all values for the given header as a List of value objects.
311      * @param name the name of the header
312      * @return the associated header values, or an empty List if none
313      */

314     public List JavaDoc getHeaders(String JavaDoc name) {
315         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
316         return (header != null ? header.getValues() : Collections.EMPTY_LIST);
317     }
318
319     public String JavaDoc encodeURL(String JavaDoc url) {
320         return url;
321     }
322
323     public String JavaDoc encodeRedirectURL(String JavaDoc url) {
324         return url;
325     }
326
327     public String JavaDoc encodeUrl(String JavaDoc url) {
328         return url;
329     }
330
331     public String JavaDoc encodeRedirectUrl(String JavaDoc url) {
332         return url;
333     }
334
335     public void sendError(int status, String JavaDoc errorMessage) throws IOException JavaDoc {
336         if (this.committed) {
337             throw new IllegalStateException JavaDoc("Cannot set error status - response is already committed");
338         }
339         this.status = status;
340         this.errorMessage = errorMessage;
341         this.committed = true;
342     }
343
344     public void sendError(int status) throws IOException JavaDoc {
345         if (this.committed) {
346             throw new IllegalStateException JavaDoc("Cannot set error status - response is already committed");
347         }
348         this.status = status;
349         this.committed = true;
350     }
351
352     public void sendRedirect(String JavaDoc url) throws IOException JavaDoc {
353         if (this.committed) {
354             throw new IllegalStateException JavaDoc("Cannot send redirect - response is already committed");
355         }
356         Assert.notNull(url, "Redirect URL must not be null");
357         this.redirectedUrl = url;
358         this.committed = true;
359     }
360
361     public String JavaDoc getRedirectedUrl() {
362         return this.redirectedUrl;
363     }
364
365     public void setDateHeader(String JavaDoc name, long value) {
366         setHeaderValue(name, new Long JavaDoc(value));
367     }
368
369     public void addDateHeader(String JavaDoc name, long value) {
370         addHeaderValue(name, new Long JavaDoc(value));
371     }
372
373     public void setHeader(String JavaDoc name, String JavaDoc value) {
374         setHeaderValue(name, value);
375     }
376
377     public void addHeader(String JavaDoc name, String JavaDoc value) {
378         addHeaderValue(name, value);
379     }
380
381     public void setIntHeader(String JavaDoc name, int value) {
382         setHeaderValue(name, new Integer JavaDoc(value));
383     }
384
385     public void addIntHeader(String JavaDoc name, int value) {
386         addHeaderValue(name, new Integer JavaDoc(value));
387     }
388
389     private void setHeaderValue(String JavaDoc name, Object JavaDoc value) {
390         doAddHeaderValue(name, value, true);
391     }
392
393     private void addHeaderValue(String JavaDoc name, Object JavaDoc value) {
394         doAddHeaderValue(name, value, false);
395     }
396
397     private void doAddHeaderValue(String JavaDoc name, Object JavaDoc value, boolean replace) {
398         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
399         Assert.notNull(value, "Header value must not be null");
400         if (header == null) {
401             header = new HeaderValueHolder();
402             this.headers.put(name, header);
403         }
404         if (replace) {
405             header.setValue(value);
406         }
407         else {
408             header.addValue(value);
409         }
410     }
411
412     public void setStatus(int status) {
413         this.status = status;
414     }
415
416     public void setStatus(int status, String JavaDoc errorMessage) {
417         this.status = status;
418         this.errorMessage = errorMessage;
419     }
420
421     public int getStatus() {
422         return this.status;
423     }
424
425     public String JavaDoc getErrorMessage() {
426         return this.errorMessage;
427     }
428
429
430     //---------------------------------------------------------------------
431
// Methods for MockRequestDispatcher
432
//---------------------------------------------------------------------
433

434     public void setForwardedUrl(String JavaDoc forwardedUrl) {
435         this.forwardedUrl = forwardedUrl;
436     }
437
438     public String JavaDoc getForwardedUrl() {
439         return this.forwardedUrl;
440     }
441
442     public void setIncludedUrl(String JavaDoc includedUrl) {
443         this.includedUrl = includedUrl;
444     }
445
446     public String JavaDoc getIncludedUrl() {
447         return this.includedUrl;
448     }
449
450 }
451
Popular Tags