001    package com.mockrunner.mock.web;
002    
003    import java.io.BufferedReader;
004    import java.io.IOException;
005    import java.io.StringReader;
006    import java.io.UnsupportedEncodingException;
007    import java.security.Principal;
008    import java.text.ParseException;
009    import java.text.SimpleDateFormat;
010    import java.util.ArrayList;
011    import java.util.Collections;
012    import java.util.Date;
013    import java.util.Enumeration;
014    import java.util.HashMap;
015    import java.util.List;
016    import java.util.Locale;
017    import java.util.Map;
018    import java.util.Vector;
019    
020    import javax.servlet.RequestDispatcher;
021    import javax.servlet.ServletContext;
022    import javax.servlet.ServletInputStream;
023    import javax.servlet.ServletRequestAttributeEvent;
024    import javax.servlet.ServletRequestAttributeListener;
025    import javax.servlet.http.Cookie;
026    import javax.servlet.http.HttpServletRequest;
027    import javax.servlet.http.HttpSession;
028    
029    /**
030     * Mock implementation of <code>HttpServletRequest</code>.
031     */
032    public class MockHttpServletRequest implements HttpServletRequest
033    {
034        private Map attributes;
035        private Map parameters;
036        private Vector locales;
037        private Map requestDispatchers;
038        private HttpSession session;
039        private String method;
040        private String authType;
041        private Map headers;
042        private String contextPath;
043        private String pathInfo;
044        private String pathTranslated;
045        private String queryString;
046        private StringBuffer requestUrl;
047        private String requestUri;
048        private String servletPath;
049        private Principal principal;
050        private String remoteUser;
051        private boolean requestedSessionIdIsFromCookie;
052        private String protocol;
053        private String serverName;
054        private int serverPort;
055        private String scheme;
056        private String remoteHost;
057        private String remoteAddr;
058        private Map roles;
059        private String characterEncoding;
060        private int contentLength;
061        private String contentType;
062        private List cookies;
063        private String bodyContent;
064        private String localAddr;
065        private String localName;
066        private int localPort;
067        private int remotePort;
068        private boolean sessionCreated;
069        private List attributeListener;
070        
071        public MockHttpServletRequest()
072        {
073            attributes = new HashMap();
074            parameters = new HashMap();
075            locales = new Vector();
076            requestDispatchers = new HashMap();
077            method = "GET";
078            headers = new HashMap();
079            requestedSessionIdIsFromCookie = true;
080            protocol = "HTTP/1.1";
081            serverName = "localhost";
082            serverPort = 8080;
083            scheme = "http";
084            remoteHost = "localhost";
085            remoteAddr = "127.0.0.1";
086            roles = new HashMap();
087            contentLength = -1;
088            cookies = new ArrayList();
089            localAddr = "127.0.0.1";
090            localName = "localhost";
091            localPort = 8080;
092            remotePort = 5000;
093            sessionCreated = false;
094            attributeListener = new ArrayList();
095        }
096        
097        public void addAttributeListener(ServletRequestAttributeListener listener)
098        {
099            attributeListener.add(listener);
100        }
101        
102        public String getParameter(String key)
103        {
104            String[] values = getParameterValues(key);
105            if (null != values && 0 < values.length)
106            {
107                return values[0];
108            }
109            return null;
110        }
111        
112        public void clearParameters()
113        {
114            parameters.clear();
115        }
116    
117        public String[] getParameterValues(String key)
118        {
119            return (String[]) parameters.get(key);
120        }
121    
122        public void setupAddParameter(String key, String[] values)
123        {
124            parameters.put(key, values);
125        }
126    
127        public void setupAddParameter(String key, String value)
128        {
129            setupAddParameter(key, new String[] { value });
130        }
131    
132        public Enumeration getParameterNames()
133        {
134            Vector parameterKeys = new Vector(parameters.keySet());
135            return parameterKeys.elements();
136        }
137    
138        public Map getParameterMap()
139        {
140            return Collections.unmodifiableMap(parameters);
141        }
142        
143        public void clearAttributes()
144        {
145            attributes.clear();
146        }
147    
148        public Object getAttribute(String key)
149        {
150            return attributes.get(key);
151        }
152    
153        public Enumeration getAttributeNames()
154        {
155            Vector attKeys = new Vector(attributes.keySet());
156            return attKeys.elements();
157        }
158    
159        public void removeAttribute(String key)
160        {
161            Object value = attributes.get(key);
162            attributes.remove(key);
163            if(null != value)
164            {
165                callAttributeListenersRemovedMethod(key, value);
166            }
167        }
168    
169        public void setAttribute(String key, Object value)
170        {
171            Object oldValue = attributes.get(key);
172            attributes.put(key, value);
173            handleAttributeListenerCalls(key, value, oldValue);
174        }
175        
176        public HttpSession getSession()
177        {
178            sessionCreated = true;
179            return session; 
180        }
181        
182        public HttpSession getSession(boolean create)
183        {
184            if(!create && !sessionCreated) return null;
185            return getSession();
186        }
187    
188        public void setSession(HttpSession session) 
189        {
190            this.session = session;   
191        }
192    
193        public RequestDispatcher getRequestDispatcher(String path)
194        {
195            RequestDispatcher dispatcher = (RequestDispatcher)requestDispatchers.get(path);
196            if(null == dispatcher)
197            {
198                dispatcher = new MockRequestDispatcher();
199                setRequestDispatcher(path, dispatcher);
200            }
201            return dispatcher;
202        }
203        
204        /**
205         * Returns the map of <code>RequestDispatcher</code> objects. The specified path
206         * maps to the corresponding <code>RequestDispatcher</code> object.
207         * @return the map of <code>RequestDispatcher</code> objects
208         */
209        public Map getRequestDispatcherMap()
210        {
211            return Collections.unmodifiableMap(requestDispatchers);
212        }
213        
214        /**
215         * Sets a <code>RequestDispatcher</code> that will be returned when calling
216         * {@link #getRequestDispatcher} with the specified path. If no <code>RequestDispatcher</code>
217         * is set for the specified path, {@link #getRequestDispatcher} automatically creates a
218         * new one.
219         * @param path the path for the <code>RequestDispatcher</code>
220         * @param dispatcher the <code>RequestDispatcher</code> object
221         */
222        public void setRequestDispatcher(String path, RequestDispatcher dispatcher)
223        {
224            if(dispatcher instanceof MockRequestDispatcher)
225            {
226                ((MockRequestDispatcher)dispatcher).setPath(path);
227            }
228            requestDispatchers.put(path, dispatcher);
229        }
230        
231        public Locale getLocale()
232        {
233            if(locales.size() < 1) return Locale.getDefault();
234            return (Locale)locales.get(0);
235        }
236    
237        public Enumeration getLocales()
238        {
239            return locales.elements();
240        }
241        
242        public void addLocale(Locale locale)
243        {
244            locales.add(locale);
245        }
246        
247        public void addLocales(List localeList)
248        {
249            locales.addAll(localeList);
250        }
251        
252        public String getMethod()
253        {
254            return method;
255        }
256    
257        public void setMethod(String method)
258        {
259            this.method = method;
260        }
261        
262        public String getAuthType()
263        {
264            return authType;
265        }
266        
267        public void setAuthType(String authType)
268        {
269            this.authType = authType;
270        }
271    
272        public long getDateHeader(String key)
273        {
274            String header = getHeader(key);
275            if(null == header) return -1;
276            try
277            {
278                Date dateValue = new SimpleDateFormat(WebConstants.DATE_FORMAT_HEADER, Locale.US).parse(header);
279                return dateValue.getTime();
280            }
281            catch (ParseException exc)
282            {
283                throw new IllegalArgumentException(exc.getMessage());
284            }
285        }
286    
287        public String getHeader(String key)
288        {
289            List headerList = (List)headers.get(key);
290            if(null == headerList || 0 == headerList.size()) return null;
291            return (String)headerList.get(0);
292        }
293    
294        public Enumeration getHeaderNames()
295        {
296            return new Vector(headers.keySet()).elements();
297        }
298    
299        public Enumeration getHeaders(String key)
300        {
301            List headerList = (List)headers.get(key);
302            if(null == headerList) return null;
303            return new Vector(headerList).elements();
304        }
305    
306        public int getIntHeader(String key)
307        {
308            String header = getHeader(key);
309            if(null == header) return -1;
310            return new Integer(header).intValue();
311        }
312        
313        public void addHeader(String key, String value)
314        {
315            List valueList = (List) headers.get(key);
316            if (null == valueList)
317            {
318                valueList = new ArrayList();
319                headers.put(key, valueList);
320            }
321            valueList.add(value);
322        }
323        
324        public void setHeader(String key, String value)
325        {
326            List valueList = new ArrayList();
327            headers.put(key, valueList);
328            valueList.add(value);
329        }
330        
331        public String getContextPath()
332        {
333            return contextPath;
334        }
335        
336        public void setContextPath(String contextPath)
337        {
338            this.contextPath = contextPath;
339        }
340        
341        public String getPathInfo()
342        {
343            return pathInfo;
344        }
345        
346        public void setPathInfo(String pathInfo)
347        {
348            this.pathInfo = pathInfo;
349        }
350        
351        public String getPathTranslated()
352        {
353            return pathTranslated;
354        }
355        
356        public void setPathTranslated(String pathTranslated)
357        {
358            this.pathTranslated = pathTranslated;
359        }
360        
361        public String getQueryString()
362        {
363            return queryString;
364        }
365        
366        public void setQueryString(String queryString)
367        {
368            this.queryString = queryString;
369        }
370        
371        public String getRequestURI()
372        {
373            return requestUri;
374        }
375        
376        public void setRequestURI(String requestUri)
377        {
378            this.requestUri = requestUri;
379        }
380        
381        public StringBuffer getRequestURL()
382        {
383            return requestUrl;
384        }
385        
386        public void setRequestURL(String requestUrl)
387        {
388            this.requestUrl = new StringBuffer(requestUrl);
389        }
390        
391        public String getServletPath()
392        {
393            return servletPath;
394        }
395        
396        public void setServletPath(String servletPath)
397        {
398            this.servletPath = servletPath;
399        }
400        
401        public Principal getUserPrincipal()
402        {
403            return principal;
404        }
405        
406        public void setUserPrincipal(Principal principal)
407        {
408            this.principal = principal;
409        }
410        
411        public String getRemoteUser()
412        {
413            return remoteUser;
414        }
415    
416        public void setRemoteUser(String remoteUser)
417        {
418            this.remoteUser = remoteUser;
419        }
420    
421        public Cookie[] getCookies()
422        {
423            return (Cookie[])cookies.toArray(new Cookie[cookies.size()]);
424        }
425        
426        public void addCookie(Cookie cookie)
427        {
428            cookies.add(cookie);
429        }
430    
431        public String getRequestedSessionId()
432        {
433            HttpSession session = getSession();
434            if(null == session) return null;
435            return session.getId();
436        }
437    
438        public boolean isRequestedSessionIdFromCookie()
439        {
440            return requestedSessionIdIsFromCookie;
441        }
442    
443        public boolean isRequestedSessionIdFromUrl()
444        {
445            return isRequestedSessionIdFromURL();
446        }
447    
448        public boolean isRequestedSessionIdFromURL()
449        {
450            return !requestedSessionIdIsFromCookie;
451        }
452        
453        public void setRequestedSessionIdFromCookie(boolean requestedSessionIdIsFromCookie)
454        {
455            this.requestedSessionIdIsFromCookie = requestedSessionIdIsFromCookie;
456        }
457    
458        public boolean isRequestedSessionIdValid()
459        {
460            HttpSession session = getSession();
461            if(null == session) return false;
462            return true;
463        }
464    
465        public boolean isUserInRole(String role)
466        {
467            return ((Boolean)roles.get(role)).booleanValue();
468        }
469        
470        public void setUserInRole(String role, boolean isInRole)
471        {
472            roles.put(role, new Boolean(isInRole));
473        }
474    
475        public String getCharacterEncoding()
476        {
477            return characterEncoding;
478        }
479        
480        public void setCharacterEncoding(String characterEncoding) throws UnsupportedEncodingException
481        {
482            this.characterEncoding = characterEncoding;
483        }
484    
485        public int getContentLength()
486        {
487            return contentLength;
488        }
489        
490        public void setContentLength(int contentLength)
491        {
492            this.contentLength = contentLength;
493        }
494    
495        public String getContentType()
496        {
497            return contentType;
498        }
499        
500        public void setContentType(String contentType)
501        {
502            this.contentType = contentType;
503        }
504    
505        public String getProtocol()
506        {
507            return protocol;
508        }
509        
510        public void setProtocol(String protocol)
511        {
512            this.protocol = protocol;
513        }
514        
515        public String getServerName()
516        {
517            return serverName;
518        }
519        
520        public void setServerName(String serverName)
521        {
522            this.serverName = serverName;
523        }
524        
525        public int getServerPort()
526        {
527            return serverPort;
528        }
529        
530        public void setServerPort(int serverPort)
531        {
532            this.serverPort = serverPort;
533        }
534        
535        public String getScheme()
536        {
537            return scheme;
538        }
539        
540        public void setScheme(String scheme)
541        {
542            this.scheme = scheme;
543        }
544        
545        public String getRemoteAddr()
546        {
547            return remoteAddr;
548        }
549        
550        public void setRemoteAddr(String remoteAddr)
551        {
552            this.remoteAddr = remoteAddr;
553        }
554        
555        public String getRemoteHost()
556        {
557            return remoteHost;
558        }
559        
560        public void setRemoteHost(String remoteHost)
561        {
562            this.remoteHost = remoteHost;
563        }
564    
565        public BufferedReader getReader() throws IOException
566        {
567            if(null == bodyContent) return null;
568            return new BufferedReader(new StringReader(bodyContent));
569        }
570        
571        public ServletInputStream getInputStream() throws IOException
572        {
573            return new MockServletInputStream(bodyContent.getBytes());
574        }
575        
576        public void setBodyContent(byte[] data)
577        {
578            setBodyContent(new String(data));
579        }
580        
581        public void setBodyContent(String bodyContent)
582        {
583            this.bodyContent = bodyContent;
584        }
585    
586        public String getRealPath(String path)
587        {
588            HttpSession session = getSession();
589            if(null == session) return null;
590            return session.getServletContext().getRealPath(path);
591        } 
592        
593        public boolean isSecure()
594        {
595            String scheme = getScheme();
596            if(null == scheme) return false;
597            return scheme.equals("https");
598        }
599        
600        public String getLocalAddr()
601        {
602            return localAddr;
603        }
604        
605        public void setLocalAddr(String localAddr)
606        {
607            this.localAddr = localAddr;
608        }
609    
610        public String getLocalName()
611        {
612            return localName;
613        }
614        
615        public void setLocalName(String localName)
616        {
617            this.localName = localName;
618        }
619    
620        public int getLocalPort()
621        {
622            return localPort;
623        }
624        
625        public void setLocalPort(int localPort)
626        {
627            this.localPort = localPort;
628        }
629    
630        public int getRemotePort()
631        {
632            return remotePort;
633        }
634    
635        public void setRemotePort(int remotePort)
636        {
637            this.remotePort = remotePort;
638        }
639        
640        private void handleAttributeListenerCalls(String key, Object value, Object oldValue)
641        {
642            if(null != oldValue)
643            {
644                if(value != null)
645                {
646                    callAttributeListenersReplacedMethod(key, oldValue);
647                }
648                else
649                {
650                    callAttributeListenersRemovedMethod(key, oldValue);
651                }
652            }
653            else
654            {
655                if(value != null)
656                {
657                    callAttributeListenersAddedMethod(key, value);
658                }
659        
660            }
661        }
662        
663        private void callAttributeListenersAddedMethod(String key, Object value)
664        {
665            for(int ii = 0; ii < attributeListener.size(); ii++)
666            {
667                ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(getServletContext(), this, key, value);
668                ((ServletRequestAttributeListener)attributeListener.get(ii)).attributeAdded(event);
669            }
670        }
671        
672        private void callAttributeListenersReplacedMethod(String key, Object value)
673        {
674            for(int ii = 0; ii < attributeListener.size(); ii++)
675            {
676                ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(getServletContext(), this, key, value);
677                ((ServletRequestAttributeListener)attributeListener.get(ii)).attributeReplaced(event);
678            }
679        }
680    
681        private void callAttributeListenersRemovedMethod(String key, Object value)
682        {
683            for(int ii = 0; ii < attributeListener.size(); ii++)
684            {
685                ServletRequestAttributeEvent event = new ServletRequestAttributeEvent(getServletContext(), this, key, value);
686                ((ServletRequestAttributeListener)attributeListener.get(ii)).attributeRemoved(event);
687            }
688        }
689        
690        private ServletContext getServletContext()
691        {
692            if(null == session) return new MockServletContext();
693            return session.getServletContext();
694        }
695    }