KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > beehive > netui > pageflow > scoping > ScopedServletUtils


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;
19
20 import org.apache.beehive.netui.pageflow.scoping.internal.ScopedRequestImpl;
21 import org.apache.beehive.netui.pageflow.scoping.internal.ScopedResponseImpl;
22
23 import javax.servlet.http.HttpServletRequest JavaDoc;
24 import javax.servlet.http.HttpServletResponse JavaDoc;
25 import javax.servlet.http.HttpSession JavaDoc;
26 import javax.servlet.ServletContext JavaDoc;
27 import javax.servlet.ServletRequest JavaDoc;
28 import javax.servlet.ServletRequestWrapper JavaDoc;
29 import javax.servlet.ServletResponse JavaDoc;
30 import javax.servlet.ServletResponseWrapper JavaDoc;
31
32 import org.apache.log4j.Logger;
33
34 import java.net.URI JavaDoc;
35 import java.net.URISyntaxException JavaDoc;
36
37
38 /**
39  * Utilities for creating scoped wrapper versions of HttpRequest, HttpResponse, ServletContext. These
40  * wrappers are the basis for a scoped servlet environment, which can be used to scope the Struts
41  * framework.
42  */

43 public class ScopedServletUtils
44 {
45     public static final String JavaDoc SCOPE_ID_PARAM = "jpfScopeID";
46     
47     static final String JavaDoc ATTR_PREFIX = "_netui:";
48     private static final String JavaDoc OVERRIDE_REQUEST_ATTR = ATTR_PREFIX + "overrideRequest";
49     private static final String JavaDoc OVERRIDE_RESPONSE_ATTR = ATTR_PREFIX + "overrideResponse";
50     
51     private static final Logger logger = Logger.getLogger( ScopedServletUtils.class );
52     
53     
54     /**
55      * Get the cached ScopedRequest wrapper. If none exists, creates one and caches it.
56      * @deprecated Use {@link #getScopedRequest(HttpServletRequest, String, ServletContext, Object, boolean)}.
57      *
58      * @param realRequest the "real" (outer) HttpServletRequest, which will be wrapped.
59      * @param overrideURI the request-URI for the wrapped object. This is a <i>webapp-relative</i> URI,
60      * i.e., it does not include the context path.
61      * @param servletContext the current ServletContext.
62      * @param scopeKey the scope-key associated with the new (or looked-up) scoped request.
63      * @return the cached (or newly-created) ScopedRequest.
64      */

65     public static ScopedRequest getScopedRequest( HttpServletRequest JavaDoc realRequest, String JavaDoc overrideURI,
66                                                   ServletContext JavaDoc servletContext, Object JavaDoc scopeKey )
67     {
68         return getScopedRequest( realRequest, overrideURI, servletContext, scopeKey, false );
69     }
70     
71     /**
72      * Get the cached ScopedRequest wrapper. If none exists, creates one and caches it.
73      *
74      * @param realRequest the "real" (outer) HttpServletRequest, which will be wrapped.
75      * @param overrideURI the request-URI for the wrapped object. This is a <i>webapp-relative</i> URI,
76      * i.e., it does not include the context path.
77      * @param servletContext the current ServletContext.
78      * @param scopeKey the scope-key associated with the new (or looked-up) scoped request.
79      * @param seeOuterRequestAttributes if <code>true</code>, a request attribute will be "seen" in the outer request,
80      * if it is not found within the scoped request; if <code>false</code>, attributes are only seen when
81      * they are present in the scoped request.
82      * @return the cached (or newly-created) ScopedRequest.
83      */

84     public static ScopedRequest getScopedRequest( HttpServletRequest JavaDoc realRequest, String JavaDoc overrideURI,
85                                                   ServletContext JavaDoc servletContext, Object JavaDoc scopeKey,
86                                                   boolean seeOuterRequestAttributes )
87     {
88         assert ! ( realRequest instanceof ScopedRequest );
89         
90         String JavaDoc requestAttr = getScopedName( OVERRIDE_REQUEST_ATTR, scopeKey );
91         ScopedRequest scopedRequest = ( ScopedRequest ) realRequest.getAttribute( requestAttr );
92         
93         //
94
// If it doesn't exist, create it and cache it.
95
//
96
if ( scopedRequest == null )
97         {
98             //
99
// The override URI must start with a slash -- it's webapp-relative.
100
//
101
if ( overrideURI != null && ! overrideURI.startsWith( "/" ) )
102             {
103                 overrideURI = "/" + overrideURI;
104             }
105             
106             scopedRequest =
107                 new ScopedRequestImpl( realRequest, overrideURI, scopeKey, servletContext, seeOuterRequestAttributes );
108             realRequest.setAttribute( requestAttr, scopedRequest );
109         }
110         
111         return scopedRequest;
112     }
113
114     /**
115      * Get the cached wrapper servlet response. If none exists, creates one and caches it.
116      *
117      * @param realResponse the "real" (outer) ServletResponse, which will be wrapped.
118      * @param scopedRequest the ScopedRequest returned from {@link #getScopedRequest}.
119      * @return the cached (or newly-created) ScopedResponse.
120      */

121     public static ScopedResponse getScopedResponse( HttpServletResponse JavaDoc realResponse,
122                                                     ScopedRequest scopedRequest )
123     {
124         assert ! ( realResponse instanceof ScopedResponse );
125         
126         String JavaDoc responseAttr = getScopedName( OVERRIDE_RESPONSE_ATTR,
127                                                                       scopedRequest.getScopeKey() );
128         HttpServletRequest JavaDoc outerRequest = scopedRequest.getOuterRequest();
129         ScopedResponse scopedResponse = ( ScopedResponse ) outerRequest.getAttribute( responseAttr );
130         
131         //
132
// If it doesn't exist, create it and cache it.
133
//
134
if ( scopedResponse == null )
135         {
136             scopedResponse = new ScopedResponseImpl( realResponse );
137             outerRequest.setAttribute( responseAttr, scopedResponse );
138         }
139         
140         return scopedResponse;
141     }
142
143     /**
144      * Find all scoped objects ({@link ScopedRequest}, {@link ScopedResponse})
145      * which have a certain scope-key, replaces this scope-key with the new one, and re-caches the objects
146      * the new scope-key.
147      * @param oldScopeKey
148      * @param newScopeKey
149      * @param request the real (outer) request, where the scoped objects are cached.
150      */

151     public static void renameScope( Object JavaDoc oldScopeKey, Object JavaDoc newScopeKey, HttpServletRequest JavaDoc request )
152     {
153         assert ! ( request instanceof ScopedRequest );
154         
155         String JavaDoc requestAttr = getScopedName( OVERRIDE_REQUEST_ATTR, oldScopeKey );
156         String JavaDoc responseAttr = getScopedName( OVERRIDE_RESPONSE_ATTR, oldScopeKey );
157         ScopedRequest scopedRequest = ( ScopedRequest ) request.getAttribute( requestAttr );
158         ScopedResponse scopedResponse = ( ScopedResponse ) request.getAttribute( responseAttr );
159         
160         if ( scopedRequest != null )
161         {
162             scopedRequest.renameScope( newScopeKey );
163             request.removeAttribute( requestAttr );
164             requestAttr = getScopedName( OVERRIDE_REQUEST_ATTR, newScopeKey );
165             request.setAttribute( requestAttr, scopedRequest );
166         }
167         else
168         {
169             ScopedRequestImpl.renameSessionScope( oldScopeKey, newScopeKey, request );
170         }
171
172         if ( scopedResponse != null )
173         {
174             request.removeAttribute( responseAttr );
175             responseAttr = getScopedName( OVERRIDE_RESPONSE_ATTR, newScopeKey );
176             request.setAttribute( responseAttr, scopedResponse );
177         }
178     }
179     
180     /**
181      * Get a scoped version of a given name.
182      *
183      * @param baseName the name to be scoped.
184      * @param scopeKey the context key for scoping the name.
185      * @return a scoped version of the given name.
186      */

187     public static String JavaDoc getScopedName( String JavaDoc baseName, Object JavaDoc scopeKey )
188     {
189         return scopeKey + baseName;
190     }
191     
192     /**
193      * Tell whether this is a scoped request.
194      *
195      * @param request the ServletRequest to test.
196      * @return <code>true</code> if the given ServletRequest is a ScopedRequest.
197      */

198     /*
199     public static boolean isScoped( ServletRequest request )
200     {
201  
202     }
203     */

204         
205     /**
206      * Get the outer (unwrapped) request.
207      *
208      * @param request the request to unwrap.
209      * @return the outer request, if the given request is a ScopedRequest (or wraps a ScopedRequest);
210      * otherwise, the given request itself.
211      */

212     public static HttpServletRequest JavaDoc getOuterRequest( HttpServletRequest JavaDoc request )
213     {
214         ScopedRequest scopedRequest = unwrapRequest( request );
215         return scopedRequest != null ? scopedRequest.getOuterRequest() : request;
216     }
217     
218     /**
219      * Get the outer (unwrapped) request.
220      *
221      * @param request the request to unwrap.
222      * @return the outer request, if the given request is a ScopedRequest (or wraps a ScopedRequest);
223      * otherwise, the given request itself.
224      */

225     public static ServletRequest JavaDoc getOuterServletRequest( ServletRequest JavaDoc request )
226     {
227         ScopedRequest scopedRequest = unwrapRequest( request );
228         return scopedRequest != null ? scopedRequest.getOuterRequest() : request;
229     }
230     
231     /**
232      * Unwraps the contained ScopedRequest from the given ServletRequest, which may be a
233      * ServletRequestWrapper.
234      *
235      * @param request the ScopedRequest, or a wrapper (ServletRequestWrapper) around it.
236      * @return the unwrapped ScopedRequest.
237      *
238      * @exclude
239      */

240     public static ScopedRequest unwrapRequest( ServletRequest JavaDoc request )
241     {
242         while ( request instanceof ServletRequestWrapper JavaDoc )
243         {
244             if ( request instanceof ScopedRequest )
245             {
246                 return ( ScopedRequest ) request;
247             }
248             else
249             {
250                 request = ( ( ServletRequestWrapper JavaDoc ) request ).getRequest();
251             }
252         }
253         
254         return null;
255     }
256     
257     /**
258      * Unwraps the contained ScopedResponseImpl from the given ServletResponse, which may be a
259      * ServletResponseWrapper.
260      *
261      * @param response the ScopedResponse, or a wrapper (ServletResponseWrapper) around it.
262      * @return the unwrapped ScopedResponseImpl.
263      *
264      * @exclude
265      */

266     public static ScopedResponse unwrapResponse( ServletResponse JavaDoc response )
267     {
268         while ( response instanceof ServletResponseWrapper JavaDoc )
269          {
270              if ( response instanceof ScopedResponse )
271              {
272                  return ( ScopedResponse ) response;
273              }
274              else
275              {
276                  response = ( ( ServletResponseWrapper JavaDoc ) response ).getResponse();
277              }
278          }
279         
280          return null;
281      }
282     
283     /**
284      * If the request is a ScopedRequest, this returns an attribute name scoped to
285      * that request's scope-ID; otherwise, it returns the given attribute name.
286      *
287      * @exclude
288      */

289     public static String JavaDoc getScopedSessionAttrName( String JavaDoc attrName, HttpServletRequest JavaDoc request )
290     {
291         String JavaDoc requestScopeParam = request.getParameter( SCOPE_ID_PARAM );
292         
293         if ( requestScopeParam != null )
294         {
295             return getScopedName( attrName, requestScopeParam );
296         }
297         
298         ScopedRequest scopedRequest = unwrapRequest( request );
299         return scopedRequest != null ? scopedRequest.getScopedName( attrName ) : attrName;
300     }
301     
302     /**
303      * If the request is a ScopedRequest, this returns an attribute whose name is scoped to that request's scope-ID;
304      * otherwise, it is a straight passthrough to {@link HttpSession#getAttribute}.
305      *
306      * @exclude
307      */

308     public static Object JavaDoc getScopedSessionAttr( String JavaDoc attrName, HttpServletRequest JavaDoc request )
309     {
310         HttpSession JavaDoc session = request.getSession( false );
311         
312         if ( session != null )
313         {
314             return session.getAttribute( getScopedSessionAttrName( attrName, request ) );
315         }
316         else
317         {
318             return null;
319         }
320     }
321
322     /**
323      * If the request is a ScopedRequest, this sets an attribute whose name is scoped to that request's scope-ID;
324      * otherwise, it is a straight passthrough to {@link HttpSession#setAttribute}.
325      *
326      * @exclude
327      */

328     public static void setScopedSessionAttr( String JavaDoc attrName, Object JavaDoc val, HttpServletRequest JavaDoc request )
329     {
330         request.getSession().setAttribute( getScopedSessionAttrName( attrName, request ), val );
331     }
332
333     /**
334      * If the request is a ScopedRequest, this removes an attribute whose name is scoped to that request's scope-ID;
335      * otherwise, it is a straight passthrough to {@link HttpSession#removeAttribute}.
336      *
337      * @exclude
338      */

339     public static void removeScopedSessionAttr( String JavaDoc attrName, HttpServletRequest JavaDoc request )
340     {
341         HttpSession JavaDoc session = request.getSession( false );
342         
343         if ( session != null )
344         {
345             session.removeAttribute( getScopedSessionAttrName( attrName, request ) );
346         }
347     }
348     
349     /**
350      * Get an attribute from the given request, and if it is a {@link ScopedRequest}, ensure that the attribute
351      * is <strong>not</strong> "showing through" from the outer request, even if the ScopedRequest allows that by
352      * default.
353      *
354      * @exclude
355      */

356     public static Object JavaDoc getScopedRequestAttribute( String JavaDoc attrName, ServletRequest JavaDoc request )
357     {
358         if ( request instanceof ScopedRequest )
359         {
360             return ( ( ScopedRequest ) request ).getAttribute( attrName, false );
361         }
362         
363         return request.getAttribute( attrName );
364     }
365     
366     /**
367      * Get the request URI, relative to the webapp root.
368      *
369      * @param request the current HttpServletRequest.
370      */

371     public static final String JavaDoc getRelativeURI( HttpServletRequest JavaDoc request )
372     {
373         return request.getServletPath();
374     }
375
376     /**
377      * Get a URI relative to the webapp root.
378      *
379      * @param request the current HttpServletRequest.
380      * @param uri the URI which should be made relative.
381      */

382     public static final String JavaDoc getRelativeURI( HttpServletRequest JavaDoc request, String JavaDoc uri )
383     {
384         return getRelativeURI( request.getContextPath(), uri );
385     }
386     
387     /**
388      * Get a URI relative to a given webapp root.
389      *
390      * @param contextPath the webapp context path, e.g., "/myWebapp"
391      * @param uri the URI which should be made relative.
392      */

393     public static final String JavaDoc getRelativeURI( String JavaDoc contextPath, String JavaDoc uri )
394     {
395         String JavaDoc requestUrl = uri;
396         int overlap = requestUrl.indexOf( contextPath + '/' );
397         assert overlap != -1 : "contextPath: " + contextPath + ", uri: " + uri;
398         return requestUrl.substring( overlap + contextPath.length() );
399     }
400
401     /**
402      * Resolve "." and ".." in a URI.
403      * @exclude
404      */

405     public static String JavaDoc normalizeURI( String JavaDoc uri )
406     {
407         //
408
// If it's a relative URI, normalize it. Note that we don't want to create a URI
409
// (very expensive) unless we think we'll need to. "./" catches "../" and "./".
410
//
411
if ( uri.indexOf( "./" ) != -1 )
412         {
413             try
414             {
415                 uri = new URI JavaDoc( uri ).normalize().toString();
416             }
417             catch ( URISyntaxException JavaDoc e )
418             {
419                 logger.error( "Could not parse relative URI " + uri );
420             }
421         }
422         
423         return uri;
424     }
425     
426     
427     /**
428      * @exclude
429      */

430     public static String JavaDoc decodeURI( HttpServletRequest JavaDoc request )
431     {
432         return request.getContextPath() + request.getServletPath(); // TODO: always decoded?
433
}
434 }
435
Popular Tags