KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > beehive > netui > pageflow > scoping > internal > ScopedRequestImpl


1 /*
2  * Copyright 2004 The Apache Software Foundation.
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  * $Header:$
17  */

18 package org.apache.beehive.netui.pageflow.scoping.internal;
19
20 import org.apache.beehive.netui.pageflow.scoping.ScopedRequest;
21 import org.apache.beehive.netui.pageflow.scoping.ScopedServletUtils;
22
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpSession JavaDoc;
25 import javax.servlet.http.HttpServletRequestWrapper JavaDoc;
26 import javax.servlet.RequestDispatcher JavaDoc;
27 import javax.servlet.ServletRequest JavaDoc;
28 import javax.servlet.ServletContext JavaDoc;
29 import java.util.Enumeration JavaDoc;
30 import java.util.Map JavaDoc;
31 import java.util.Collections JavaDoc;
32 import java.util.ArrayList JavaDoc;
33 import java.util.Iterator JavaDoc;
34 import java.util.HashMap JavaDoc;
35 import java.util.List JavaDoc;
36 import java.util.Set JavaDoc;
37 import java.util.HashSet JavaDoc;
38 import java.io.UnsupportedEncodingException JavaDoc;
39
40 import org.apache.log4j.Logger;
41 import org.apache.commons.codec.net.URLCodec;
42 import org.apache.commons.codec.DecoderException;
43
44
45 /**
46  * A wrapper around HttpServletRequest, associated with a given scope-key. All calls to setAttribute,
47  * getAttribute, removeAttribute, etc. are scoped to this object, while most other functionality
48  * delegates to the wrapped HttpServletRequest.
49  * Instances of this class also keep track of their own request-URIs, which are independent of the
50  * wrapped request-URIs.
51  */

52 public class ScopedRequestImpl
53         extends HttpServletRequestWrapper JavaDoc
54         implements ScopedRequest
55 {
56     private String JavaDoc _requestURI;
57     private String JavaDoc _servletPath;
58     private String JavaDoc _forwardedURI;
59     private ScopedAttributeContainer _scopedContainer;
60     private List JavaDoc _listenScopes;
61     private String JavaDoc _overridePathInfo = null;
62     private boolean _isActiveRequest = false;
63     private boolean _seeOuterRequestAttributes = false;
64     private Set JavaDoc _visibleOuterRequestAttrs;
65     private Map JavaDoc _additionalParameters;
66
67
68     static final String JavaDoc ATTR_PREFIX = "_netui:";
69     private static final String JavaDoc OUR_SESSION_ATTR = ATTR_PREFIX + "scopedSession";
70     private static final String JavaDoc STORED_ATTRS_ATTR = ATTR_PREFIX + "storedAttrs";
71
72     private static final Logger _log = Logger.getLogger( ScopedRequestImpl.class );
73     private static final URLCodec URL_CODEC = new URLCodec();
74
75
76     public ScopedRequestImpl( HttpServletRequest JavaDoc req, String JavaDoc overrideRequestURI, Object JavaDoc scopeKey,
77                               ServletContext JavaDoc servletContext, boolean seeOuterRequestAttributes )
78     {
79         super( req );
80         
81         _scopedContainer = new ScopedAttributeContainer( scopeKey );
82         setRequestURI( overrideRequestURI );
83         _seeOuterRequestAttributes = seeOuterRequestAttributes;
84         
85         if ( ! seeOuterRequestAttributes ) _visibleOuterRequestAttrs = new HashSet JavaDoc();
86     }
87
88     /**
89      * @deprecated Use {@link #ScopedRequestImpl(HttpServletRequest, String, Object, ServletContext, boolean)}.
90      */

91     public ScopedRequestImpl( HttpServletRequest JavaDoc req, String JavaDoc overrideRequestURI, Object JavaDoc scopeKey,
92                               ServletContext JavaDoc context )
93     {
94         this( req, overrideRequestURI, scopeKey, context, false );
95     }
96
97     public String JavaDoc getRequestedSessionId()
98     {
99         return super.getRequestedSessionId();
100     }
101
102     public String JavaDoc getRequestURI()
103     {
104         return _requestURI;
105     }
106
107     public void setRequestURI( String JavaDoc uri )
108     {
109         _requestURI = uri;
110         
111         if ( uri == null )
112         {
113             _servletPath = null;
114             return;
115         }
116         
117         //
118
// Set the servlet path (decoded)
119
//
120
assert uri.startsWith( getOuterRequest().getContextPath() ) : uri;
121         setServletPath( uri.substring( getOuterRequest().getContextPath().length() ) );
122     }
123         
124     public void setRequestURI( String JavaDoc contextPath, String JavaDoc servletPath )
125     {
126         _requestURI = contextPath + servletPath;
127         setServletPath( servletPath );
128     }
129     
130     private void setServletPath( String JavaDoc servletPath )
131     {
132         String JavaDoc encoding = getCharacterEncoding();
133         
134         try
135         {
136             if ( encoding == null ) encoding = "utf-8";
137             servletPath = URL_CODEC.decode( servletPath, encoding );
138         }
139         catch ( DecoderException e )
140         {
141             _log.error( "error decoding path " + servletPath, e );
142         }
143         catch ( UnsupportedEncodingException JavaDoc e )
144         {
145             _log.error( "unsupported encoding " + encoding + " while decoding path " + servletPath, e );
146         }
147         
148         _servletPath = ScopedServletUtils.normalizeURI( servletPath );
149     }
150     
151     public StringBuffer JavaDoc getRequestURL()
152     {
153         HttpServletRequest JavaDoc outerRequest = getOuterRequest();
154         StringBuffer JavaDoc url = new StringBuffer JavaDoc( outerRequest.getScheme() );
155         url.append( "://" ).append( outerRequest.getServerName() );
156         url.append( ':' ).append( outerRequest.getServerPort() );
157         url.append( getRequestURI() );
158         return url;
159     }
160
161     public String JavaDoc getServletPath()
162     {
163         return _servletPath;
164     }
165
166     public String JavaDoc getParameter( String JavaDoc paramName )
167     {
168         String JavaDoc retVal = getLocalParameter( paramName );
169         if ( retVal == null )
170         {
171             retVal = getListenScopeParameter( paramName );
172         }
173         
174         return retVal;
175     }
176
177     /**
178      * Add a parameter to the request.
179      *
180      * @param name the parameter name.
181      * @param value the parameter value.
182      */

183     public void addParameter( String JavaDoc name, String JavaDoc value )
184     {
185         if ( _additionalParameters == null )
186         {
187             _additionalParameters = new HashMap JavaDoc();
188         }
189         
190         _additionalParameters.put( name, value );
191     }
192     
193     /**
194      * Get the parameter from the scoped request only (don't check in listen scoped requests)
195      * @param paramName
196      * @return value of the parameter
197      */

198     public String JavaDoc getLocalParameter( String JavaDoc paramName )
199     {
200         if ( _additionalParameters != null )
201         {
202             String JavaDoc overrideParam = ( String JavaDoc ) _additionalParameters.get( paramName );
203
204             if ( overrideParam != null )
205             {
206                 return overrideParam;
207             }
208         }
209
210         ServletRequest JavaDoc request = getRequest();
211         String JavaDoc retVal = request.getParameter( _scopedContainer.getScopedName( paramName ) );
212
213         if ( retVal == null && _isActiveRequest && paramName.startsWith( AUTOSCOPE_PREFIX ) )
214         {
215             retVal = request.getParameter( paramName );
216         }
217         
218         return retVal;
219     }
220
221     /**
222      * Get the parameter from the listen scoped requests
223      * @param paramName
224      * @return value of the parameter
225      */

226     public String JavaDoc getListenScopeParameter( String JavaDoc paramName )
227     {
228         String JavaDoc retVal = null;
229
230         if ( _listenScopes != null )
231         {
232             for ( int i = 0, len = _listenScopes.size(); retVal == null && i < len; ++i )
233             {
234                 String JavaDoc key = ScopedServletUtils.getScopedName( paramName, _listenScopes.get( i ) );
235                 retVal = getRequest().getParameter( key );
236             }
237         }
238
239         return retVal;
240     }
241
242     
243     public Enumeration JavaDoc getParameterNames()
244     {
245         ArrayList JavaDoc paramNames = new ArrayList JavaDoc();
246
247         for ( Enumeration JavaDoc e = getRequest().getParameterNames(); e.hasMoreElements(); )
248         {
249             String JavaDoc scopedParamName = ( String JavaDoc ) e.nextElement();
250
251             if ( _scopedContainer.isInScope( scopedParamName ) )
252             {
253                 paramNames.add( _scopedContainer.removeScope( scopedParamName ) );
254             }
255             else if ( _isActiveRequest && scopedParamName.startsWith( AUTOSCOPE_PREFIX ) )
256             {
257                 paramNames.add( scopedParamName );
258             }
259             else if ( _listenScopes != null )
260             {
261                 for ( int i = 0, len = _listenScopes.size(); i < len; ++i )
262                 {
263                     Object JavaDoc scope = _listenScopes.get( i );
264
265                     if ( ScopedAttributeContainer.isInScope( scopedParamName, scope ) )
266                     {
267                         paramNames.add( ScopedAttributeContainer.removeScope( scopedParamName, scope ) );
268                     }
269                 }
270             }
271         }
272
273         return Collections.enumeration( paramNames );
274     }
275
276     public String JavaDoc[] getParameterValues( String JavaDoc paramName )
277     {
278         ServletRequest JavaDoc request = getRequest();
279         String JavaDoc[] retVals = request.getParameterValues( _scopedContainer.getScopedName( paramName ) );
280
281         if ( retVals == null && _isActiveRequest && paramName.startsWith( AUTOSCOPE_PREFIX ) )
282         {
283             retVals = request.getParameterValues( paramName );
284         }
285
286         if ( retVals == null && _listenScopes != null )
287         {
288             for ( int i = 0, len = _listenScopes.size(); retVals == null && i < len; ++i )
289             {
290                 String JavaDoc key = ScopedServletUtils.getScopedName( paramName, _listenScopes.get( i ) );
291                 retVals = request.getParameterValues( key );
292             }
293         }
294
295         return retVals;
296     }
297
298     public Map JavaDoc getParameterMap()
299     {
300         return filterParameterMap( getRequest().getParameterMap() );
301     }
302     
303     /**
304      * @exclude
305      */

306     public Map JavaDoc filterParameterMap( Map JavaDoc parameterMap )
307     {
308         HashMap JavaDoc map = new HashMap JavaDoc();
309
310         for ( Iterator JavaDoc i = parameterMap.entrySet().iterator(); i.hasNext(); )
311         {
312             Map.Entry JavaDoc entry = ( Map.Entry JavaDoc ) i.next();
313             String JavaDoc scopedParamName = ( String JavaDoc ) entry.getKey();
314
315             if ( _scopedContainer.isInScope( scopedParamName ) )
316             {
317                 map.put( _scopedContainer.removeScope( scopedParamName ), entry.getValue() );
318             }
319             else if ( _isActiveRequest && scopedParamName.startsWith( AUTOSCOPE_PREFIX ) )
320             {
321                 map.put( scopedParamName, entry.getValue() );
322             }
323             else if ( _listenScopes != null )
324             {
325                 for ( int j = 0, len = _listenScopes.size(); j < len; ++j )
326                 {
327                     if ( ScopedAttributeContainer.isInScope( scopedParamName, _listenScopes.get( j ) ) )
328                     {
329                         map.put( ScopedAttributeContainer.removeScope( scopedParamName, _listenScopes.get( j ) ),
330                                  entry.getValue() );
331                     }
332                 }
333             }
334         }
335
336         return map;
337     }
338
339     /**
340      * Adds a scope to "listen" to. This scope will see all request parameters from a ScopedRequest
341      * of the given scope.
342      */

343     public void addListenScope( Object JavaDoc scopeKey )
344     {
345         assert scopeKey != null;
346
347         if ( _listenScopes == null )
348         {
349             _listenScopes = new ArrayList JavaDoc();
350         }
351
352         _listenScopes.add( scopeKey );
353     }
354
355     public RequestDispatcher JavaDoc getRequestDispatcher( String JavaDoc uri )
356     {
357         return new ScopedRequestDispatcher( uri );
358     }
359
360     public void doForward()
361     {
362         String JavaDoc forwardedURI = _forwardedURI;
363         
364         if ( forwardedURI != null )
365         {
366             if ( ! forwardedURI.startsWith( "/" ) )
367             {
368                 int lastSlash = _requestURI.lastIndexOf( '/' );
369                 assert lastSlash != -1 : _requestURI;
370                 setRequestURI( _requestURI.substring( 0, lastSlash + 1 ) + forwardedURI );
371             }
372             else
373             {
374                 setRequestURI( getOuterRequest().getContextPath(), forwardedURI );
375             }
376             
377             // Parse the query string and add parameters to the internal map
378
parseQueryParameters();
379         }
380         else
381         {
382             setRequestURI( null );
383         }
384     }
385
386     private void parseQueryParameters()
387     {
388         int queryIndex = _requestURI.indexOf("?");
389         if (queryIndex < 0)
390         {
391             return;
392         }
393
394         String JavaDoc queryString = _requestURI.substring(queryIndex + 1);
395
396         // hack off the query string
397
_requestURI = _requestURI.substring(0, queryIndex);
398
399         if (queryString.length() == 0)
400         {
401             return;
402         }
403
404         HashMap JavaDoc queryParameters = new HashMap JavaDoc();
405         ParseUtils.parseQueryString(queryString, queryParameters, getCharacterEncoding());
406
407         Iterator JavaDoc itor = queryParameters.keySet().iterator();
408         while (itor.hasNext())
409         {
410             Object JavaDoc key = itor.next();
411             addParameter((String JavaDoc) key, (String JavaDoc) queryParameters.get(key));
412         }
413     }
414
415     /**
416      * Simply stores the URI that was being forwarded to.
417      *
418      * @param uri
419      */

420     public void setForwardedURI( String JavaDoc uri )
421     {
422         _forwardedURI = uri;
423     }
424
425     public String JavaDoc getForwardedURI()
426     {
427         return _forwardedURI;
428     }
429
430     /**
431      * @deprecated Use {@link ScopedResponseImpl#didRedirect} instead.
432      */

433     public boolean didRedirect()
434     {
435         return false;
436     }
437
438     /**
439      * Stores the current map of request attributes in the Session.
440      */

441     public void persistAttributes()
442     {
443         String JavaDoc attrName = getScopedName( STORED_ATTRS_ATTR );
444         getSession().setAttribute( attrName, _scopedContainer.getSerializableAttrs() );
445     }
446
447     /**
448      * Restores the map of request attributes from a map saved in the Session.
449      */

450     public void restoreAttributes()
451     {
452         String JavaDoc attrName = getScopedName( STORED_ATTRS_ATTR );
453         Map JavaDoc savedAttrs = ( Map JavaDoc ) getSession().getAttribute( attrName );
454         Map JavaDoc currentAttrs = _scopedContainer.getAttrMap();
455         
456         if ( savedAttrs != null )
457         {
458             if ( currentAttrs != null )
459             {
460                 savedAttrs.putAll( currentAttrs );
461             }
462             
463             _scopedContainer.setAttrMap( savedAttrs );
464         }
465     }
466
467     public final HttpServletRequest JavaDoc getOuterRequest()
468     {
469         return ( HttpServletRequest JavaDoc ) getRequest();
470     }
471
472     public final Object JavaDoc getAttribute( String JavaDoc attrName )
473     {
474         return getAttribute( attrName, true );
475     }
476     
477     public final Object JavaDoc getAttribute( String JavaDoc attrName, boolean allowOuterRequestAttributes )
478     {
479         if ( ! allowOuterRequestAttributes ) return _scopedContainer.getAttribute( attrName );
480         
481         ServletRequest JavaDoc outerRequest = getRequest();
482         
483         if ( ! _seeOuterRequestAttributes && _visibleOuterRequestAttrs.contains( attrName ) )
484         {
485             return outerRequest.getAttribute( attrName );
486         }
487
488         Object JavaDoc value = _scopedContainer.getAttribute( attrName );
489         
490         if ( value == null && _seeOuterRequestAttributes )
491         {
492             value = outerRequest.getAttribute( attrName );
493         }
494         
495         return value;
496     }
497
498     public final void setAttribute( String JavaDoc attrName, Object JavaDoc o )
499     {
500         if ( ! _seeOuterRequestAttributes && _visibleOuterRequestAttrs.contains( attrName ) )
501         {
502             getRequest().setAttribute( attrName, o );
503         }
504         else
505         {
506             _scopedContainer.setAttribute( attrName, o );
507         }
508     }
509
510     public final Enumeration JavaDoc getAttributeNames()
511     {
512         Set JavaDoc set = new HashSet JavaDoc();
513
514         if ( ! _seeOuterRequestAttributes )
515         {
516             for ( Enumeration JavaDoc e = getRequest().getAttributeNames(); e.hasMoreElements(); )
517             {
518                 Object JavaDoc attrName = e.nextElement();
519                 if ( _visibleOuterRequestAttrs.contains( attrName ) ) set.add( attrName );
520             }
521         }
522
523         for ( Enumeration JavaDoc e = _scopedContainer.getAttributeNames(); e.hasMoreElements(); )
524         {
525             set.add( e.nextElement() );
526         }
527         
528         if ( _seeOuterRequestAttributes )
529         {
530             for ( Enumeration JavaDoc e = getRequest().getAttributeNames(); e.hasMoreElements(); )
531             {
532                 set.add( e.nextElement() );
533             }
534         }
535
536         return Collections.enumeration( set );
537     }
538
539     public final void removeAttribute( String JavaDoc attrName )
540     {
541         if ( ! _seeOuterRequestAttributes && _visibleOuterRequestAttrs.contains( attrName ) )
542         {
543             getRequest().removeAttribute( attrName );
544         }
545         else
546         {
547             _scopedContainer.removeAttribute( attrName );
548         }
549     }
550
551     public void registerOuterAttribute( String JavaDoc attrName )
552     {
553         assert ! _seeOuterRequestAttributes :
554                 "(attribute " + attrName + ") " +
555                 "this method is not valid unless the ScopedRequest is configured not to see outer request attributes";
556         _visibleOuterRequestAttrs.add( attrName );
557     }
558
559     public final Object JavaDoc getScopeKey()
560     {
561         return _scopedContainer.getScopeKey();
562     }
563
564     public void renameScope( Object JavaDoc newScopeKey )
565     {
566         _scopedContainer.renameScope( newScopeKey );
567     }
568
569     public static void renameSessionScope( Object JavaDoc oldScopeKey, Object JavaDoc newScopeKey, HttpServletRequest JavaDoc outerRequest )
570     {
571         HttpSession JavaDoc realSession = outerRequest.getSession( false );
572
573         if ( realSession != null )
574         {
575             String JavaDoc realSessionAttr = ScopedServletUtils.getScopedName( OUR_SESSION_ATTR, oldScopeKey );
576             Object JavaDoc ourSession = realSession.getAttribute( realSessionAttr );
577             realSessionAttr = ScopedServletUtils.getScopedName( OUR_SESSION_ATTR, newScopeKey );
578             realSession.setAttribute( realSessionAttr, ourSession );
579         }
580     }
581
582     public String JavaDoc getPathInfo()
583     {
584         return _overridePathInfo;
585     }
586
587     public void setPathInfo( String JavaDoc pathInfo )
588     {
589         _overridePathInfo = pathInfo;
590     }
591
592     /**
593      * Makes this request listen to specially-prefixed request parameters.
594      */

595     public void setActiveRequest()
596     {
597         _isActiveRequest = true;
598     }
599     
600     public final String JavaDoc getScopedName( String JavaDoc baseName )
601     {
602         return _scopedContainer.getScopedName( baseName );
603     }
604
605     /**
606      * see if this scoped request is listening to any other scoped request
607      * @return true if has listen scopes
608      */

609     public boolean hasListenScopes()
610     {
611          return _listenScopes != null && _listenScopes.size() > 0;
612     }
613 }
614
615
Popular Tags