KickJava   Java API By Example, From Geeks To Geeks.

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


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.BufferedReader JavaDoc;
20 import java.io.ByteArrayInputStream JavaDoc;
21 import java.io.InputStream JavaDoc;
22 import java.io.InputStreamReader JavaDoc;
23 import java.io.Reader JavaDoc;
24 import java.io.UnsupportedEncodingException JavaDoc;
25 import java.security.Principal JavaDoc;
26 import java.util.Collection JavaDoc;
27 import java.util.Collections JavaDoc;
28 import java.util.Date JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.HashSet JavaDoc;
31 import java.util.Hashtable JavaDoc;
32 import java.util.Locale JavaDoc;
33 import java.util.Map JavaDoc;
34 import java.util.Set JavaDoc;
35 import java.util.Vector JavaDoc;
36
37 import javax.servlet.RequestDispatcher JavaDoc;
38 import javax.servlet.ServletContext JavaDoc;
39 import javax.servlet.ServletInputStream JavaDoc;
40 import javax.servlet.http.Cookie JavaDoc;
41 import javax.servlet.http.HttpServletRequest JavaDoc;
42 import javax.servlet.http.HttpSession JavaDoc;
43
44 import org.springframework.core.CollectionFactory;
45 import org.springframework.util.Assert;
46
47 /**
48  * Mock implementation of the {@link javax.servlet.http.HttpServletRequest}
49  * interface. Supports the Servlet 2.4 API level.
50  *
51  * <p>Used for testing the web framework; also useful for testing
52  * application controllers.
53  *
54  * @author Juergen Hoeller
55  * @author Rod Johnson
56  * @author Rick Evans
57  * @since 1.0.2
58  */

59 public class MockHttpServletRequest implements HttpServletRequest JavaDoc {
60
61     /**
62      * The default protocol: 'http'.
63      */

64     public static final String JavaDoc DEFAULT_PROTOCOL = "http";
65
66     /**
67      * The default server address: '127.0.0.1'.
68      */

69     public static final String JavaDoc DEFAULT_SERVER_ADDR = "127.0.0.1";
70
71     /**
72      * The default server name: 'localhost'.
73      */

74     public static final String JavaDoc DEFAULT_SERVER_NAME = "localhost";
75
76     /**
77      * The default server port: '80'.
78      */

79     public static final int DEFAULT_SERVER_PORT = 80;
80
81     /**
82      * The default remote address: '127.0.0.1'.
83      */

84     public static final String JavaDoc DEFAULT_REMOTE_ADDR = "127.0.0.1";
85
86     /**
87      * The default remote host: 'localhost'.
88      */

89     public static final String JavaDoc DEFAULT_REMOTE_HOST = "localhost";
90
91
92     private boolean active = true;
93
94
95     //---------------------------------------------------------------------
96
// ServletRequest properties
97
//---------------------------------------------------------------------
98

99     private final Hashtable JavaDoc attributes = new Hashtable JavaDoc();
100
101     private String JavaDoc characterEncoding;
102
103     private byte[] content;
104
105     private String JavaDoc contentType;
106
107     private final Map JavaDoc parameters = CollectionFactory.createLinkedMapIfPossible(16);
108
109     private String JavaDoc protocol = DEFAULT_PROTOCOL;
110
111     private String JavaDoc scheme = DEFAULT_PROTOCOL;
112
113     private String JavaDoc serverName = DEFAULT_SERVER_NAME;
114
115     private int serverPort = DEFAULT_SERVER_PORT;
116
117     private String JavaDoc remoteAddr = DEFAULT_REMOTE_ADDR;
118
119     private String JavaDoc remoteHost = DEFAULT_REMOTE_HOST;
120
121     /** List of locales in descending order */
122     private final Vector JavaDoc locales = new Vector JavaDoc();
123
124     private boolean secure = false;
125
126     private final ServletContext JavaDoc servletContext;
127
128     private int remotePort = DEFAULT_SERVER_PORT;
129
130     private String JavaDoc localName = DEFAULT_SERVER_NAME;
131
132     private String JavaDoc localAddr = DEFAULT_SERVER_ADDR;
133
134     private int localPort = DEFAULT_SERVER_PORT;
135
136
137     //---------------------------------------------------------------------
138
// HttpServletRequest properties
139
//---------------------------------------------------------------------
140

141     private String JavaDoc authType;
142
143     private Cookie JavaDoc[] cookies;
144
145     /**
146      * The key is the lowercase header name; the value is a {@link HeaderValueHolder} object.
147      */

148     private final Hashtable JavaDoc headers = new Hashtable JavaDoc();
149
150     private String JavaDoc method;
151
152     private String JavaDoc pathInfo;
153
154     private String JavaDoc contextPath = "";
155
156     private String JavaDoc queryString;
157
158     private String JavaDoc remoteUser;
159
160     private final Set JavaDoc userRoles = new HashSet JavaDoc();
161
162     private Principal JavaDoc userPrincipal;
163
164     private String JavaDoc requestURI;
165
166     private String JavaDoc servletPath = "";
167
168     private HttpSession JavaDoc session;
169
170     private boolean requestedSessionIdValid = true;
171
172     private boolean requestedSessionIdFromCookie = true;
173
174     private boolean requestedSessionIdFromURL = false;
175
176
177     //---------------------------------------------------------------------
178
// Constructors
179
//---------------------------------------------------------------------
180

181     /**
182      * Create a new MockHttpServletRequest with a default
183      * {@link MockServletContext}.
184      * @see MockServletContext
185      */

186     public MockHttpServletRequest() {
187         this(null, "", "");
188     }
189
190     /**
191      * Create a new MockHttpServletRequest with a default
192      * {@link MockServletContext}.
193      * @param method the request method (may be <code>null</code>)
194      * @param requestURI the request URI (may be <code>null</code>)
195      * @see #setMethod
196      * @see #setRequestURI
197      * @see MockServletContext
198      */

199     public MockHttpServletRequest(String JavaDoc method, String JavaDoc requestURI) {
200         this(null, method, requestURI);
201     }
202
203     /**
204      * Create a new MockHttpServletRequest.
205      * @param servletContext the ServletContext that the request runs in
206      * (may be <code>null</code> to use a default MockServletContext)
207      * @see MockServletContext
208      */

209     public MockHttpServletRequest(ServletContext JavaDoc servletContext) {
210         this(servletContext, "", "");
211     }
212
213     /**
214      * Create a new MockHttpServletRequest.
215      * @param servletContext the ServletContext that the request runs in
216      * (may be <code>null</code> to use a default MockServletContext)
217      * @param method the request method (may be <code>null</code>)
218      * @param requestURI the request URI (may be <code>null</code>)
219      * @see #setMethod
220      * @see #setRequestURI
221      * @see MockServletContext
222      */

223     public MockHttpServletRequest(ServletContext JavaDoc servletContext, String JavaDoc method, String JavaDoc requestURI) {
224         this.servletContext = (servletContext != null ? servletContext : new MockServletContext());
225         this.method = method;
226         this.requestURI = requestURI;
227         this.locales.add(Locale.ENGLISH);
228     }
229
230
231     //---------------------------------------------------------------------
232
// Lifecycle methods
233
//---------------------------------------------------------------------
234

235     /**
236      * Return whether this request is still active (that is, not completed yet).
237      */

238     public boolean isActive() {
239         return this.active;
240     }
241
242     /**
243      * Mark this request as completed, keeping its state.
244      */

245     public void close() {
246         this.active = false;
247     }
248
249     /**
250      * Invalidate this request, clearing its state.
251      */

252     public void invalidate() {
253         close();
254         clearAttributes();
255     }
256
257     /**
258      * Check whether this request is still active (that is, not completed yet),
259      * throwing an IllegalStateException if not active anymore.
260      */

261     protected void checkActive() throws IllegalStateException JavaDoc {
262         if (!this.active) {
263             throw new IllegalStateException JavaDoc("Request is not active anymore");
264         }
265     }
266
267
268     //---------------------------------------------------------------------
269
// ServletRequest interface
270
//---------------------------------------------------------------------
271

272     public Object JavaDoc getAttribute(String JavaDoc name) {
273         checkActive();
274         return this.attributes.get(name);
275     }
276
277     public Enumeration JavaDoc getAttributeNames() {
278         checkActive();
279         return this.attributes.keys();
280     }
281
282     public String JavaDoc getCharacterEncoding() {
283         return this.characterEncoding;
284     }
285
286     public void setCharacterEncoding(String JavaDoc characterEncoding) {
287         this.characterEncoding = characterEncoding;
288     }
289
290     public void setContent(byte[] content) {
291         this.content = content;
292     }
293
294     public int getContentLength() {
295         return (this.content != null ? this.content.length : -1);
296     }
297
298     public void setContentType(String JavaDoc contentType) {
299         this.contentType = contentType;
300     }
301
302     public String JavaDoc getContentType() {
303         return this.contentType;
304     }
305
306     public ServletInputStream JavaDoc getInputStream() {
307         if (this.content != null) {
308             return new DelegatingServletInputStream(new ByteArrayInputStream JavaDoc(this.content));
309         }
310         else {
311             return null;
312         }
313     }
314
315     /**
316      * Set a single value for the specified HTTP parameter.
317      * <p>If there are already one or more values registered for the given
318      * parameter name, they will be replaced.
319      */

320     public void setParameter(String JavaDoc name, String JavaDoc value) {
321         setParameter(name, new String JavaDoc[] {value});
322     }
323
324     /**
325      * Set an array of values for the specified HTTP parameter.
326      * <p>If there are already one or more values registered for the given
327      * parameter name, they will be replaced.
328      */

329     public void setParameter(String JavaDoc name, String JavaDoc[] values) {
330         Assert.notNull(name, "Parameter name must not be null");
331         this.parameters.put(name, values);
332     }
333
334     /**
335      * Add a single value for the specified HTTP parameter.
336      * <p>If there are already one or more values registered for the given
337      * parameter name, the given value will be added to the end of the list.
338      */

339     public void addParameter(String JavaDoc name, String JavaDoc value) {
340         addParameter(name, new String JavaDoc[] {value});
341     }
342
343     /**
344      * Add an array of values for the specified HTTP parameter.
345      * <p>If there are already one or more values registered for the given
346      * parameter name, the given values will be added to the end of the list.
347      */

348     public void addParameter(String JavaDoc name, String JavaDoc[] values) {
349         Assert.notNull(name, "Parameter name must not be null");
350         String JavaDoc[] oldArr = (String JavaDoc[]) this.parameters.get(name);
351         if (oldArr != null) {
352             String JavaDoc[] newArr = new String JavaDoc[oldArr.length + values.length];
353             System.arraycopy(oldArr, 0, newArr, 0, oldArr.length);
354             System.arraycopy(values, 0, newArr, oldArr.length, values.length);
355             this.parameters.put(name, newArr);
356         }
357         else {
358             this.parameters.put(name, values);
359         }
360     }
361
362     /**
363      * Remove already registered values for the specified HTTP parameter, if any.
364      */

365     public void removeParameter(String JavaDoc name) {
366         Assert.notNull(name, "Parameter name must not be null");
367         this.parameters.remove(name);
368     }
369
370     public String JavaDoc getParameter(String JavaDoc name) {
371         Assert.notNull(name, "Parameter name must not be null");
372         String JavaDoc[] arr = (String JavaDoc[]) this.parameters.get(name);
373         return (arr != null && arr.length > 0 ? arr[0] : null);
374     }
375
376     public Enumeration JavaDoc getParameterNames() {
377         return Collections.enumeration(this.parameters.keySet());
378     }
379
380     public String JavaDoc[] getParameterValues(String JavaDoc name) {
381         Assert.notNull(name, "Parameter name must not be null");
382         return (String JavaDoc[]) this.parameters.get(name);
383     }
384
385     public Map JavaDoc getParameterMap() {
386         return Collections.unmodifiableMap(this.parameters);
387     }
388
389     public void setProtocol(String JavaDoc protocol) {
390         this.protocol = protocol;
391     }
392
393     public String JavaDoc getProtocol() {
394         return this.protocol;
395     }
396
397     public void setScheme(String JavaDoc scheme) {
398         this.scheme = scheme;
399     }
400
401     public String JavaDoc getScheme() {
402         return this.scheme;
403     }
404
405     public void setServerName(String JavaDoc serverName) {
406         this.serverName = serverName;
407     }
408
409     public String JavaDoc getServerName() {
410         return this.serverName;
411     }
412
413     public void setServerPort(int serverPort) {
414         this.serverPort = serverPort;
415     }
416
417     public int getServerPort() {
418         return this.serverPort;
419     }
420
421     public BufferedReader JavaDoc getReader() throws UnsupportedEncodingException JavaDoc {
422         if (this.content != null) {
423             InputStream JavaDoc sourceStream = new ByteArrayInputStream JavaDoc(this.content);
424             Reader JavaDoc sourceReader = (this.characterEncoding != null) ?
425                     new InputStreamReader JavaDoc(sourceStream, this.characterEncoding) : new InputStreamReader JavaDoc(sourceStream);
426             return new BufferedReader JavaDoc(sourceReader);
427         }
428         else {
429             return null;
430         }
431     }
432
433     public void setRemoteAddr(String JavaDoc remoteAddr) {
434         this.remoteAddr = remoteAddr;
435     }
436
437     public String JavaDoc getRemoteAddr() {
438         return this.remoteAddr;
439     }
440
441     public void setRemoteHost(String JavaDoc remoteHost) {
442         this.remoteHost = remoteHost;
443     }
444
445     public String JavaDoc getRemoteHost() {
446         return this.remoteHost;
447     }
448
449     public void setAttribute(String JavaDoc name, Object JavaDoc value) {
450         checkActive();
451         Assert.notNull(name, "Attribute name must not be null");
452         if (value != null) {
453             this.attributes.put(name, value);
454         }
455         else {
456             this.attributes.remove(name);
457         }
458     }
459
460     public void removeAttribute(String JavaDoc name) {
461         checkActive();
462         Assert.notNull(name, "Attribute name must not be null");
463         this.attributes.remove(name);
464     }
465
466     /**
467      * Clear all of this request's attributes.
468      */

469     public void clearAttributes() {
470         this.attributes.clear();
471     }
472
473     /**
474      * Add a new preferred locale, before any existing locales.
475      */

476     public void addPreferredLocale(Locale JavaDoc locale) {
477         Assert.notNull(locale, "Locale must not be null");
478         this.locales.add(0, locale);
479     }
480
481     public Locale JavaDoc getLocale() {
482         return (Locale JavaDoc) this.locales.get(0);
483     }
484
485     public Enumeration JavaDoc getLocales() {
486         return this.locales.elements();
487     }
488
489     public void setSecure(boolean secure) {
490         this.secure = secure;
491     }
492
493     public boolean isSecure() {
494         return this.secure;
495     }
496
497     public RequestDispatcher JavaDoc getRequestDispatcher(String JavaDoc path) {
498         return new MockRequestDispatcher(path);
499     }
500
501     public String JavaDoc getRealPath(String JavaDoc path) {
502         return this.servletContext.getRealPath(path);
503     }
504
505     public void setRemotePort(int remotePort) {
506         this.remotePort = remotePort;
507     }
508
509     public int getRemotePort() {
510         return this.remotePort;
511     }
512
513     public void setLocalName(String JavaDoc localName) {
514         this.localName = localName;
515     }
516
517     public String JavaDoc getLocalName() {
518         return this.localName;
519     }
520
521     public void setLocalAddr(String JavaDoc localAddr) {
522         this.localAddr = localAddr;
523     }
524
525     public String JavaDoc getLocalAddr() {
526         return this.localAddr;
527     }
528
529     public void setLocalPort(int localPort) {
530         this.localPort = localPort;
531     }
532
533     public int getLocalPort() {
534         return this.localPort;
535     }
536
537
538     //---------------------------------------------------------------------
539
// HttpServletRequest interface
540
//---------------------------------------------------------------------
541

542     public void setAuthType(String JavaDoc authType) {
543         this.authType = authType;
544     }
545
546     public String JavaDoc getAuthType() {
547         return this.authType;
548     }
549
550     public void setCookies(Cookie JavaDoc[] cookies) {
551         this.cookies = cookies;
552     }
553
554     public Cookie JavaDoc[] getCookies() {
555         return this.cookies;
556     }
557
558     /**
559      * Add a header entry for the given name.
560      * <p>If there was no entry for that header name before,
561      * the value will be used as-is. In case of an existing entry,
562      * a String array will be created, adding the given value (more
563      * specifically, its toString representation) as further element.
564      * <p>Multiple values can only be stored as list of Strings,
565      * following the Servlet spec (see <code>getHeaders</code> accessor).
566      * As alternative to repeated <code>addHeader</code> calls for
567      * individual elements, you can use a single call with an entire
568      * array or Collection of values as parameter.
569      * @see #getHeaderNames
570      * @see #getHeader
571      * @see #getHeaders
572      * @see #getDateHeader
573      * @see #getIntHeader
574      */

575     public void addHeader(String JavaDoc name, Object JavaDoc value) {
576         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
577         Assert.notNull(value, "Header value must not be null");
578         if (header == null) {
579             header = new HeaderValueHolder();
580             this.headers.put(name, header);
581         }
582         if (value instanceof Collection JavaDoc) {
583             header.addValues((Collection JavaDoc) value);
584         }
585         else if (value.getClass().isArray()) {
586             header.addValueArray(value);
587         }
588         else {
589             header.addValue(value);
590         }
591     }
592
593     public long getDateHeader(String JavaDoc name) {
594         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
595         Object JavaDoc value = (header != null ? header.getValue() : null);
596         if (value instanceof Date JavaDoc) {
597             return ((Date JavaDoc) value).getTime();
598         }
599         else if (value instanceof Number JavaDoc) {
600             return ((Number JavaDoc) value).longValue();
601         }
602         else if (value != null) {
603             throw new IllegalArgumentException JavaDoc(
604                     "Value for header '" + name + "' is neither a Date nor a Number: " + value);
605         }
606         else {
607             return -1L;
608         }
609     }
610
611     public String JavaDoc getHeader(String JavaDoc name) {
612         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
613         return (header != null ? header.getValue().toString() : null);
614     }
615
616     public Enumeration JavaDoc getHeaders(String JavaDoc name) {
617         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
618         return Collections.enumeration(header != null ? header.getValues() : Collections.EMPTY_LIST);
619     }
620
621     public Enumeration JavaDoc getHeaderNames() {
622         return this.headers.keys();
623     }
624
625     public int getIntHeader(String JavaDoc name) {
626         HeaderValueHolder header = HeaderValueHolder.getByName(this.headers, name);
627         Object JavaDoc value = (header != null ? header.getValue() : null);
628         if (value instanceof Number JavaDoc) {
629             return ((Number JavaDoc) value).intValue();
630         }
631         else if (value instanceof String JavaDoc) {
632             return Integer.parseInt((String JavaDoc) value);
633         }
634         else if (value != null) {
635             throw new NumberFormatException JavaDoc("Value for header '" + name + "' is not a Number: " + value);
636         }
637         else {
638             return -1;
639         }
640     }
641
642     public void setMethod(String JavaDoc method) {
643         this.method = method;
644     }
645
646     public String JavaDoc getMethod() {
647         return this.method;
648     }
649
650     public void setPathInfo(String JavaDoc pathInfo) {
651         this.pathInfo = pathInfo;
652     }
653
654     public String JavaDoc getPathInfo() {
655         return this.pathInfo;
656     }
657
658     public String JavaDoc getPathTranslated() {
659         return (this.pathInfo != null ? getRealPath(this.pathInfo) : null);
660     }
661
662     public void setContextPath(String JavaDoc contextPath) {
663         this.contextPath = contextPath;
664     }
665
666     public String JavaDoc getContextPath() {
667         return this.contextPath;
668     }
669
670     public void setQueryString(String JavaDoc queryString) {
671         this.queryString = queryString;
672     }
673
674     public String JavaDoc getQueryString() {
675         return this.queryString;
676     }
677
678     public void setRemoteUser(String JavaDoc remoteUser) {
679         this.remoteUser = remoteUser;
680     }
681
682     public String JavaDoc getRemoteUser() {
683         return this.remoteUser;
684     }
685
686     /**
687      * @deprecated in favor of addUserRole
688      * @see #addUserRole
689      */

690     public void addRole(String JavaDoc role) {
691         addUserRole(role);
692     }
693
694     public void addUserRole(String JavaDoc role) {
695         this.userRoles.add(role);
696     }
697
698     public boolean isUserInRole(String JavaDoc role) {
699         return this.userRoles.contains(role);
700     }
701
702     public void setUserPrincipal(Principal JavaDoc userPrincipal) {
703         this.userPrincipal = userPrincipal;
704     }
705
706     public Principal JavaDoc getUserPrincipal() {
707         return this.userPrincipal;
708     }
709
710     public String JavaDoc getRequestedSessionId() {
711         HttpSession JavaDoc session = getSession();
712         return (session != null ? session.getId() : null);
713     }
714
715     public void setRequestURI(String JavaDoc requestURI) {
716         this.requestURI = requestURI;
717     }
718
719     public String JavaDoc getRequestURI() {
720         return this.requestURI;
721     }
722
723     public StringBuffer JavaDoc getRequestURL() {
724         StringBuffer JavaDoc url = new StringBuffer JavaDoc(this.scheme);
725         url.append("://").append(this.serverName).append(':').append(this.serverPort);
726         url.append(getRequestURI());
727         return url;
728     }
729
730     public void setServletPath(String JavaDoc servletPath) {
731         this.servletPath = servletPath;
732     }
733
734     public String JavaDoc getServletPath() {
735         return this.servletPath;
736     }
737
738     public void setSession(HttpSession JavaDoc session) {
739         this.session = session;
740         if (session instanceof MockHttpSession) {
741             MockHttpSession mockSession = ((MockHttpSession) session);
742             mockSession.access();
743         }
744     }
745
746     public HttpSession JavaDoc getSession(boolean create) {
747         checkActive();
748         // Reset session if invalidated.
749
if (this.session instanceof MockHttpSession && ((MockHttpSession) this.session).isInvalid()) {
750             this.session = null;
751         }
752         // Create new session if necessary.
753
if (this.session == null && create) {
754             this.session = new MockHttpSession(this.servletContext);
755         }
756         return this.session;
757     }
758
759     public HttpSession JavaDoc getSession() {
760         return getSession(true);
761     }
762
763     public void setRequestedSessionIdValid(boolean requestedSessionIdValid) {
764         this.requestedSessionIdValid = requestedSessionIdValid;
765     }
766
767     public boolean isRequestedSessionIdValid() {
768         return this.requestedSessionIdValid;
769     }
770
771     public void setRequestedSessionIdFromCookie(boolean requestedSessionIdFromCookie) {
772         this.requestedSessionIdFromCookie = requestedSessionIdFromCookie;
773     }
774
775     public boolean isRequestedSessionIdFromCookie() {
776         return this.requestedSessionIdFromCookie;
777     }
778
779     public void setRequestedSessionIdFromURL(boolean requestedSessionIdFromURL) {
780         this.requestedSessionIdFromURL = requestedSessionIdFromURL;
781     }
782
783     public boolean isRequestedSessionIdFromURL() {
784         return this.requestedSessionIdFromURL;
785     }
786
787     public boolean isRequestedSessionIdFromUrl() {
788         return isRequestedSessionIdFromURL();
789     }
790
791 }
792
Popular Tags