2009/05/20 - Apache Shale has been retired.

For more information, please explore the Attic.

View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to you under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.shale.test.mock;
19  
20  import java.io.BufferedReader;
21  import java.security.Principal;
22  import java.text.ParseException;
23  import java.text.SimpleDateFormat;
24  import java.util.ArrayList;
25  import java.util.Date;
26  import java.util.Enumeration;
27  import java.util.HashMap;
28  import java.util.Iterator;
29  import java.util.List;
30  import java.util.Locale;
31  import java.util.Map;
32  import java.util.TimeZone;
33  import java.util.Vector;
34  
35  import javax.servlet.RequestDispatcher;
36  import javax.servlet.ServletContext;
37  import javax.servlet.ServletInputStream;
38  import javax.servlet.ServletRequestAttributeEvent;
39  import javax.servlet.ServletRequestAttributeListener;
40  import javax.servlet.http.Cookie;
41  import javax.servlet.http.HttpServletRequest;
42  import javax.servlet.http.HttpSession;
43  
44  
45  /***
46   * <p>Mock implementation of <code>HttpServletContext</code>.</p>
47   *
48   * $Id$
49   */
50  
51  public class MockHttpServletRequest implements HttpServletRequest {
52  
53  
54      // ------------------------------------------------------------ Constructors
55  
56  
57      public MockHttpServletRequest() {
58  
59          super();
60  
61      }
62  
63  
64      public MockHttpServletRequest(HttpSession session) {
65  
66          super();
67          setHttpSession(session);
68  
69      }
70  
71  
72      public MockHttpServletRequest(String contextPath, String servletPath,
73                                    String pathInfo, String queryString) {
74  
75          super();
76          setPathElements(contextPath, servletPath, pathInfo, queryString);
77  
78      }
79  
80  
81  
82      public MockHttpServletRequest(String contextPath, String servletPath,
83                                    String pathInfo, String queryString,
84                                    HttpSession session) {
85  
86          super();
87          setPathElements(contextPath, servletPath, pathInfo, queryString);
88          setHttpSession(session);
89  
90      }
91  
92  
93      // ----------------------------------------------------- Mock Object Methods
94  
95  
96      /***
97       * <p>Add a new listener instance that should be notified about
98       * attribute changes.</p>
99       *
100      * @param listener The new listener to register
101      */
102     public void addAttributeListener(ServletRequestAttributeListener listener) {
103         attributeListeners.add(listener);
104     }
105 
106 
107     /***
108      * <p>Add a date-valued header for this request.</p>
109      *
110      * @param name Header name
111      * @param value Header value
112      */
113     public void addDateHeader(String name, long value) {
114 
115         headers.add(name + ": " + formatDate(value));
116 
117     }
118 
119 
120     /***
121      * <p>Add a String-valued header for this request.</p>
122      *
123      * @param name Header name
124      * @param value Header value
125      */
126     public void addHeader(String name, String value) {
127 
128         headers.add(name + ": " + value);
129 
130     }
131 
132 
133     /***
134      * <p>Add an integer-valued header for this request.</p>
135      *
136      * @param name Header name
137      * @param value Header value
138      */
139     public void addIntHeader(String name, int value) {
140 
141         headers.add(name + ": " + value);
142 
143     }
144 
145 
146     /***
147      * <p>Add a request parameter for this request.</p>
148      *
149      * @param name Parameter name
150      * @param value Parameter value
151      */
152     public void addParameter(String name, String value) {
153 
154         String[] values = (String[]) parameters.get(name);
155         if (values == null) {
156             String[] results = new String[] { value };
157             parameters.put(name, results);
158             return;
159         }
160         String[] results = new String[values.length + 1];
161         System.arraycopy(values, 0, results, 0, values.length);
162         results[values.length] = value;
163         parameters.put(name, results);
164 
165     }
166 
167 
168     /***
169      * <p>Return the <code>ServletContext</code> associated with
170      * this request.</p>
171      */
172     public ServletContext getServletContext() {
173 
174         return this.servletContext;
175 
176     }
177 
178 
179     /***
180      * <p>Set the <code>HttpSession</code> associated with this request.</p>
181      *
182      * @param session The new session
183      */
184     public void setHttpSession(HttpSession session) {
185 
186         this.session = session;
187 
188     }
189 
190 
191     /***
192      * <p>Set the <code>Locale</code> associated with this request.</p>
193      *
194      * @param locale The new locale
195      */
196     public void setLocale(Locale locale) {
197 
198         this.locale = locale;
199 
200     }
201 
202 
203     /***
204      * <p>Set the parsed path elements associated with this request.</p>
205      *
206      * @param contextPath The context path
207      * @param servletPath The servlet path
208      * @param pathInfo The extra path information
209      * @param queryString The query string
210      */
211     public void setPathElements(String contextPath, String servletPath,
212                                 String pathInfo, String queryString) {
213 
214         this.contextPath = contextPath;
215         this.servletPath = servletPath;
216         this.pathInfo = pathInfo;
217         this.queryString = queryString;
218 
219     }
220 
221 
222     /***
223      * <p>Set the <code>ServletContext</code> associated with this request.</p>
224      *
225      * @param servletContext The new servlet context
226      */
227     public void setServletContext(ServletContext servletContext) {
228 
229         this.servletContext = servletContext;
230 
231     }
232 
233 
234     /***
235      * <p>Set the <code>Principal</code> associated with this request.</p>
236      *
237      * @param principal The new Principal
238      */
239     public void setUserPrincipal(Principal principal) {
240 
241         this.principal = principal;
242 
243     }
244 
245 
246     // ------------------------------------------------------ Instance Variables
247 
248 
249     private List attributeListeners = new ArrayList();
250     private HashMap attributes = new HashMap();
251     private String contextPath = null;
252     private List headers = new ArrayList();
253     private Locale locale = null;
254     private HashMap parameters = new HashMap();
255     private String pathInfo = null;
256     private Principal principal = null;
257     private String queryString = null;
258     private ServletContext servletContext = null;
259     private String servletPath = null;
260     private HttpSession session = null;
261 
262 
263     // ---------------------------------------------- HttpServletRequest Methods
264 
265 
266     /*** {@inheritDoc} */
267     public String getAuthType() {
268 
269         throw new UnsupportedOperationException();
270 
271     }
272 
273 
274     /*** {@inheritDoc} */
275     public String getContextPath() {
276 
277         return contextPath;
278 
279     }
280 
281 
282     /*** {@inheritDoc} */
283     public Cookie[] getCookies() {
284 
285         throw new UnsupportedOperationException();
286 
287     }
288 
289 
290     /*** {@inheritDoc} */
291     public long getDateHeader(String name) {
292 
293         String match = name + ":";
294         Iterator headers = this.headers.iterator();
295         while (headers.hasNext()) {
296             String header = (String) headers.next();
297             if (header.startsWith(match)) {
298                 return parseDate(header.substring(match.length() + 1).trim());
299             }
300         }
301         return (long) -1;
302 
303     }
304 
305 
306     /*** {@inheritDoc} */
307     public String getHeader(String name) {
308 
309         String match = name + ":";
310         Iterator headers = this.headers.iterator();
311         while (headers.hasNext()) {
312             String header = (String) headers.next();
313             if (header.startsWith(match)) {
314                 return header.substring(match.length() + 1).trim();
315             }
316         }
317         return null;
318 
319     }
320 
321 
322     /*** {@inheritDoc} */
323     public Enumeration getHeaderNames() {
324 
325         Vector values = new Vector();
326         Iterator headers = this.headers.iterator();
327         while (headers.hasNext()) {
328             String header = (String) headers.next();
329             int colon = header.indexOf(':');
330             if (colon >= 0) {
331                 String name = header.substring(0, colon).trim();
332                 if (!values.contains(name)) {
333                     values.add(name);
334                 }
335             }
336         }
337         return values.elements();
338 
339     }
340 
341 
342     /*** {@inheritDoc} */
343     public Enumeration getHeaders(String name) {
344 
345         String match = name + ":";
346         Vector values = new Vector();
347         Iterator headers = this.headers.iterator();
348         while (headers.hasNext()) {
349             String header = (String) headers.next();
350             if (header.startsWith(match)) {
351                 values.add(header.substring(match.length() + 1).trim());
352             }
353         }
354         return values.elements();
355 
356     }
357 
358 
359     /*** {@inheritDoc} */
360     public int getIntHeader(String name) {
361 
362         String match = name + ":";
363         Iterator headers = this.headers.iterator();
364         while (headers.hasNext()) {
365             String header = (String) headers.next();
366             if (header.startsWith(match)) {
367                 return Integer.parseInt(header.substring(match.length() + 1).trim());
368             }
369         }
370         return -1;
371 
372     }
373 
374 
375     /*** {@inheritDoc} */
376     public String getMethod() {
377 
378         throw new UnsupportedOperationException();
379 
380     }
381 
382 
383     /*** {@inheritDoc} */
384     public String getPathInfo() {
385 
386         return pathInfo;
387 
388     }
389 
390 
391     /*** {@inheritDoc} */
392     public String getPathTranslated() {
393 
394         throw new UnsupportedOperationException();
395 
396     }
397 
398 
399     /*** {@inheritDoc} */
400     public String getQueryString() {
401 
402         return queryString;
403 
404     }
405 
406 
407     /*** {@inheritDoc} */
408     public String getRemoteUser() {
409 
410         if (principal != null) {
411             return principal.getName();
412         } else {
413             return null;
414         }
415 
416     }
417 
418 
419     /*** {@inheritDoc} */
420     public String getRequestedSessionId() {
421 
422         throw new UnsupportedOperationException();
423 
424     }
425 
426 
427     /*** {@inheritDoc} */
428     public String getRequestURI() {
429 
430         StringBuffer sb = new StringBuffer();
431         if (contextPath != null) {
432             sb.append(contextPath);
433         }
434         if (servletPath != null) {
435             sb.append(servletPath);
436         }
437         if (pathInfo != null) {
438             sb.append(pathInfo);
439         }
440         if (sb.length() > 0) {
441             return sb.toString();
442         }
443         throw new UnsupportedOperationException();
444 
445     }
446 
447 
448     /*** {@inheritDoc} */
449     public StringBuffer getRequestURL() {
450 
451         throw new UnsupportedOperationException();
452 
453     }
454 
455 
456     /*** {@inheritDoc} */
457     public String getServletPath() {
458 
459         return (servletPath);
460 
461     }
462 
463 
464     /*** {@inheritDoc} */
465     public HttpSession getSession() {
466 
467         return getSession(true);
468 
469     }
470 
471 
472     /*** {@inheritDoc} */
473     public HttpSession getSession(boolean create) {
474 
475         if (create && (session == null)) {
476             throw new UnsupportedOperationException();
477         }
478         return session;
479 
480     }
481 
482 
483     /*** {@inheritDoc} */
484     public Principal getUserPrincipal() {
485 
486         return principal;
487 
488     }
489 
490 
491     /*** {@inheritDoc} */
492     public boolean isRequestedSessionIdFromCookie() {
493 
494         throw new UnsupportedOperationException();
495 
496     }
497 
498 
499     /*** {@inheritDoc} */
500     public boolean isRequestedSessionIdFromUrl() {
501 
502         throw new UnsupportedOperationException();
503 
504     }
505 
506 
507     /*** {@inheritDoc} */
508     public boolean isRequestedSessionIdFromURL() {
509 
510         throw new UnsupportedOperationException();
511 
512     }
513 
514 
515     /*** {@inheritDoc} */
516     public boolean isRequestedSessionIdValid() {
517 
518         throw new UnsupportedOperationException();
519 
520     }
521 
522 
523     /*** {@inheritDoc} */
524     public boolean isUserInRole(String role) {
525 
526         throw new UnsupportedOperationException();
527 
528     }
529 
530 
531     // ------------------------------------------------- ServletRequest Methods
532 
533 
534     /*** {@inheritDoc} */
535     public Object getAttribute(String name) {
536 
537         return attributes.get(name);
538 
539     }
540 
541 
542     /*** {@inheritDoc} */
543     public Enumeration getAttributeNames() {
544 
545         return new MockEnumeration(attributes.keySet().iterator());
546 
547     }
548 
549 
550     /*** {@inheritDoc} */
551     public String getCharacterEncoding() {
552 
553         throw new UnsupportedOperationException();
554 
555     }
556 
557 
558     /*** {@inheritDoc} */
559     public int getContentLength() {
560 
561         throw new UnsupportedOperationException();
562 
563     }
564 
565 
566     /*** {@inheritDoc} */
567     public String getContentType() {
568 
569         throw new UnsupportedOperationException();
570 
571     }
572 
573 
574     /*** {@inheritDoc} */
575     public ServletInputStream getInputStream() {
576 
577         throw new UnsupportedOperationException();
578 
579     }
580 
581 
582     /*** {@inheritDoc} */
583     public Locale getLocale() {
584 
585         return locale;
586 
587     }
588 
589 
590     /*** {@inheritDoc} */
591     public Enumeration getLocales() {
592 
593         throw new UnsupportedOperationException();
594 
595     }
596 
597 
598     /*** {@inheritDoc} */
599     public String getLocalAddr() {
600 
601         throw new UnsupportedOperationException();
602 
603     }
604 
605 
606     /*** {@inheritDoc} */
607     public String getLocalName() {
608 
609         throw new UnsupportedOperationException();
610 
611     }
612 
613 
614     /*** {@inheritDoc} */
615     public int getLocalPort() {
616 
617         throw new UnsupportedOperationException();
618 
619     }
620 
621 
622     /*** {@inheritDoc} */
623     public String getParameter(String name) {
624 
625         String[] values = (String[]) parameters.get(name);
626         if (values != null) {
627             return values[0];
628         } else {
629             return null;
630         }
631 
632     }
633 
634 
635     /*** {@inheritDoc} */
636     public Map getParameterMap() {
637 
638         return parameters;
639 
640     }
641 
642 
643     /*** {@inheritDoc} */
644     public Enumeration getParameterNames() {
645 
646         return new MockEnumeration(parameters.keySet().iterator());
647 
648     }
649 
650 
651     /*** {@inheritDoc} */
652     public String[] getParameterValues(String name) {
653 
654         return (String[]) parameters.get(name);
655 
656     }
657 
658 
659     /*** {@inheritDoc} */
660     public String getProtocol() {
661 
662         throw new UnsupportedOperationException();
663 
664     }
665 
666 
667     /*** {@inheritDoc} */
668     public BufferedReader getReader() {
669 
670         throw new UnsupportedOperationException();
671 
672     }
673 
674 
675     /*** {@inheritDoc} */
676     public String getRealPath(String path) {
677 
678         throw new UnsupportedOperationException();
679 
680     }
681 
682 
683     /*** {@inheritDoc} */
684     public String getRemoteAddr() {
685 
686         // i figure testing never assumes a specific remote - so anything works
687         return "1.2.3.4";
688 
689     }
690 
691 
692     /*** {@inheritDoc} */
693     public String getRemoteHost() {
694 
695         // i figure testing never assumes a specific remote - so anything works
696         return "ShaleServer";
697 
698     }
699 
700 
701     /*** {@inheritDoc} */
702     public int getRemotePort() {
703 
704         // i figure testing never assumes a specific remote - so anything works
705         return 46123;
706 
707     }
708 
709 
710     /*** {@inheritDoc} */
711     public RequestDispatcher getRequestDispatcher(String path) {
712 
713         throw new UnsupportedOperationException();
714 
715     }
716 
717 
718     /*** {@inheritDoc} */
719     public String getScheme() {
720 
721         return ("http");
722 
723     }
724 
725 
726     /*** {@inheritDoc} */
727     public String getServerName() {
728 
729         return ("localhost");
730 
731     }
732 
733 
734     /*** {@inheritDoc} */
735     public int getServerPort() {
736 
737         return (8080);
738 
739     }
740 
741 
742     /*** {@inheritDoc} */
743     public boolean isSecure() {
744 
745         return false;
746 
747     }
748 
749 
750     /*** {@inheritDoc} */
751     public void removeAttribute(String name) {
752 
753         if (attributes.containsKey(name)) {
754             Object value = attributes.remove(name);
755             fireAttributeRemoved(name, value);
756         }
757 
758     }
759 
760 
761     /*** {@inheritDoc} */
762     public void setAttribute(String name, Object value) {
763 
764         if (name == null) {
765             throw new IllegalArgumentException("Attribute name cannot be null");
766         }
767         if (value == null) {
768             removeAttribute(name);
769             return;
770         }
771         if (attributes.containsKey(name)) {
772             Object oldValue = attributes.get(name);
773             attributes.put(name, value);
774             fireAttributeReplaced(name, oldValue);
775         } else {
776             attributes.put(name, value);
777             fireAttributeAdded(name, value);
778         }
779 
780     }
781 
782 
783     /*** {@inheritDoc} */
784     public void setCharacterEncoding(String name) {
785 
786         throw new UnsupportedOperationException();
787 
788     }
789 
790 
791     // --------------------------------------------------------- Private Methods
792 
793 
794     /***
795      * <p>Fire an attribute added event to interested listeners.</p>
796      *
797      * @param key Attribute key whose value was added
798      * @param value The new attribute value
799      */
800     private void fireAttributeAdded(String key, Object value) {
801         if (attributeListeners.size() < 1) {
802             return;
803         }
804         ServletRequestAttributeEvent event =
805                 new ServletRequestAttributeEvent(getServletContext(), this, key, value);
806         Iterator listeners = attributeListeners.iterator();
807         while (listeners.hasNext()) {
808             ServletRequestAttributeListener listener =
809                     (ServletRequestAttributeListener) listeners.next();
810             listener.attributeAdded(event);
811         }
812     }
813 
814 
815     /***
816      * <p>Fire an attribute removed event to interested listeners.</p>
817      *
818      * @param key Attribute key whose value was removed
819      * @param value Attribute value that was removed
820      */
821     private void fireAttributeRemoved(String key, Object value) {
822         if (attributeListeners.size() < 1) {
823             return;
824         }
825         ServletRequestAttributeEvent event =
826                 new ServletRequestAttributeEvent(getServletContext(), this, key, value);
827         Iterator listeners = attributeListeners.iterator();
828         while (listeners.hasNext()) {
829             ServletRequestAttributeListener listener =
830                     (ServletRequestAttributeListener) listeners.next();
831             listener.attributeRemoved(event);
832         }
833     }
834 
835 
836     /***
837      * <p>Fire an attribute replaced event to interested listeners.</p>
838      *
839      * @param key Attribute key whose value was replaced
840      * @param value The original value
841      */
842     private void fireAttributeReplaced(String key, Object value) {
843         if (attributeListeners.size() < 1) {
844             return;
845         }
846         ServletRequestAttributeEvent event =
847                 new ServletRequestAttributeEvent(getServletContext(), this, key, value);
848         Iterator listeners = attributeListeners.iterator();
849         while (listeners.hasNext()) {
850             ServletRequestAttributeListener listener =
851                     (ServletRequestAttributeListener) listeners.next();
852             listener.attributeReplaced(event);
853         }
854     }
855 
856 
857     /***
858      * <p>The date formatting helper we will use in <code>httpTimestamp()</code>.
859      * Note that usage of this helper must be synchronized.</p>
860      */
861     private static SimpleDateFormat format =
862             new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
863     static {
864         format.setTimeZone(TimeZone.getTimeZone("GMT"));
865     }
866 
867 
868     /***
869      * <p>Return a properly formatted String version of the specified
870      * date/time, formatted as required by the HTTP specification.</p>
871      *
872      * @param date Date/time, expressed as milliseconds since the epoch
873      */
874     private String formatDate(long date) {
875         return format.format(new Date(date));
876     }
877 
878 
879     /***
880      * <p>Return a date/time value, parsed from the specified String.</p>
881      *
882      * @param date Date/time, expressed as a String
883      */
884     private long parseDate(String date) {
885         try {
886             return format.parse(date).getTime();
887         } catch (ParseException e) {
888             throw new IllegalArgumentException(date);
889         }
890     }
891 
892 
893 }