KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > jasper > runtime > PageContextImpl


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.jasper.runtime;
19
20 import java.io.IOException JavaDoc;
21 import java.io.Writer JavaDoc;
22 import java.security.AccessController JavaDoc;
23 import java.security.PrivilegedAction JavaDoc;
24 import java.security.PrivilegedActionException JavaDoc;
25 import java.security.PrivilegedExceptionAction JavaDoc;
26 import java.util.Enumeration JavaDoc;
27 import java.util.HashMap JavaDoc;
28
29 import javax.el.ELContext;
30 import javax.el.ExpressionFactory;
31 import javax.el.ValueExpression;
32 import javax.servlet.Servlet JavaDoc;
33 import javax.servlet.ServletConfig JavaDoc;
34 import javax.servlet.ServletContext JavaDoc;
35 import javax.servlet.ServletException JavaDoc;
36 import javax.servlet.ServletRequest JavaDoc;
37 import javax.servlet.ServletResponse JavaDoc;
38 import javax.servlet.http.HttpServletRequest JavaDoc;
39 import javax.servlet.http.HttpServletResponse JavaDoc;
40 import javax.servlet.http.HttpSession JavaDoc;
41 import javax.servlet.jsp.JspException JavaDoc;
42 import javax.servlet.jsp.JspFactory JavaDoc;
43 import javax.servlet.jsp.JspWriter JavaDoc;
44 import javax.servlet.jsp.PageContext JavaDoc;
45 import javax.servlet.jsp.el.ELException JavaDoc;
46 import javax.servlet.jsp.el.ExpressionEvaluator JavaDoc;
47 import javax.servlet.jsp.el.VariableResolver JavaDoc;
48 import javax.servlet.jsp.tagext.BodyContent JavaDoc;
49
50 import org.apache.commons.logging.Log;
51 import org.apache.commons.logging.LogFactory;
52 import org.apache.jasper.Constants;
53 import org.apache.jasper.compiler.Localizer;
54 import org.apache.jasper.el.ELContextImpl;
55 import org.apache.jasper.el.ExpressionEvaluatorImpl;
56 import org.apache.jasper.el.FunctionMapperImpl;
57 import org.apache.jasper.el.VariableResolverImpl;
58 import org.apache.jasper.security.SecurityUtil;
59 import org.apache.jasper.util.Enumerator;
60
61 /**
62  * Implementation of the PageContext class from the JSP spec. Also doubles as a
63  * VariableResolver for the EL.
64  *
65  * @author Anil K. Vijendran
66  * @author Larry Cable
67  * @author Hans Bergsten
68  * @author Pierre Delisle
69  * @author Mark Roth
70  * @author Jan Luehe
71  * @author Jacob Hookom
72  */

73 public class PageContextImpl extends PageContext JavaDoc {
74
75     // Logger
76
private static Log log = LogFactory.getLog(PageContextImpl.class);
77
78     private BodyContentImpl[] outs;
79
80     private int depth;
81
82     // per-servlet state
83
private Servlet JavaDoc servlet;
84
85     private ServletConfig JavaDoc config;
86
87     private ServletContext JavaDoc context;
88
89     private JspApplicationContextImpl applicationContext;
90
91     private String JavaDoc errorPageURL;
92
93     // page-scope attributes
94
private transient HashMap JavaDoc<String JavaDoc, Object JavaDoc> attributes;
95
96     // per-request state
97
private transient ServletRequest JavaDoc request;
98
99     private transient ServletResponse JavaDoc response;
100
101     private transient HttpSession JavaDoc session;
102     
103     private transient ELContextImpl elContext;
104
105     private boolean isIncluded;
106     
107     
108     // initial output stream
109
private transient JspWriter JavaDoc out;
110
111     private transient JspWriterImpl baseOut;
112
113     /*
114      * Constructor.
115      */

116     PageContextImpl() {
117         this.outs = new BodyContentImpl[0];
118         this.attributes = new HashMap JavaDoc<String JavaDoc, Object JavaDoc>(16);
119         this.depth = -1;
120     }
121
122     public void initialize(Servlet JavaDoc servlet, ServletRequest JavaDoc request,
123             ServletResponse JavaDoc response, String JavaDoc errorPageURL,
124             boolean needsSession, int bufferSize, boolean autoFlush)
125             throws IOException JavaDoc {
126
127         _initialize(servlet, request, response, errorPageURL, needsSession,
128                 bufferSize, autoFlush);
129     }
130
131     private void _initialize(Servlet JavaDoc servlet, ServletRequest JavaDoc request,
132             ServletResponse JavaDoc response, String JavaDoc errorPageURL,
133             boolean needsSession, int bufferSize, boolean autoFlush)
134             throws IOException JavaDoc {
135
136         // initialize state
137
this.servlet = servlet;
138         this.config = servlet.getServletConfig();
139         this.context = config.getServletContext();
140         this.errorPageURL = errorPageURL;
141         this.request = request;
142         this.response = response;
143         
144         // initialize application context
145
this.applicationContext = JspApplicationContextImpl.getInstance(context);
146
147         // Setup session (if required)
148
if (request instanceof HttpServletRequest JavaDoc && needsSession)
149             this.session = ((HttpServletRequest JavaDoc) request).getSession();
150         if (needsSession && session == null)
151             throw new IllegalStateException JavaDoc(
152                     "Page needs a session and none is available");
153
154         // initialize the initial out ...
155
depth = -1;
156         if (this.baseOut == null) {
157             this.baseOut = new JspWriterImpl(response, bufferSize, autoFlush);
158         } else {
159             this.baseOut.init(response, bufferSize, autoFlush);
160         }
161         this.out = baseOut;
162
163         // register names/values as per spec
164
setAttribute(OUT, this.out);
165         setAttribute(REQUEST, request);
166         setAttribute(RESPONSE, response);
167
168         if (session != null)
169             setAttribute(SESSION, session);
170
171         setAttribute(PAGE, servlet);
172         setAttribute(CONFIG, config);
173         setAttribute(PAGECONTEXT, this);
174         setAttribute(APPLICATION, context);
175
176         isIncluded = request.getAttribute("javax.servlet.include.servlet_path") != null;
177     }
178
179     public void release() {
180         out = baseOut;
181         try {
182             if (isIncluded) {
183                 ((JspWriterImpl) out).flushBuffer();
184                 // push it into the including jspWriter
185
} else {
186                 // Old code:
187
// out.flush();
188
// Do not flush the buffer even if we're not included (i.e.
189
// we are the main page. The servlet will flush it and close
190
// the stream.
191
((JspWriterImpl) out).flushBuffer();
192             }
193         } catch (IOException JavaDoc ex) {
194             IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc(Localizer.getMessage("jsp.error.flush"), ex);
195             throw ise;
196         } finally {
197             servlet = null;
198             config = null;
199             context = null;
200             applicationContext = null;
201             elContext = null;
202             errorPageURL = null;
203             request = null;
204             response = null;
205             depth = -1;
206             baseOut.recycle();
207             session = null;
208             attributes.clear();
209         }
210     }
211
212     public Object JavaDoc getAttribute(final String JavaDoc name) {
213
214         if (name == null) {
215             throw new NullPointerException JavaDoc(Localizer
216                     .getMessage("jsp.error.attribute.null_name"));
217         }
218
219         if (SecurityUtil.isPackageProtectionEnabled()) {
220             return AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
221                 public Object JavaDoc run() {
222                     return doGetAttribute(name);
223                 }
224             });
225         } else {
226             return doGetAttribute(name);
227         }
228
229     }
230
231     private Object JavaDoc doGetAttribute(String JavaDoc name) {
232         return attributes.get(name);
233     }
234
235     public Object JavaDoc getAttribute(final String JavaDoc name, final int scope) {
236
237         if (name == null) {
238             throw new NullPointerException JavaDoc(Localizer
239                     .getMessage("jsp.error.attribute.null_name"));
240         }
241
242         if (SecurityUtil.isPackageProtectionEnabled()) {
243             return AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
244                 public Object JavaDoc run() {
245                     return doGetAttribute(name, scope);
246                 }
247             });
248         } else {
249             return doGetAttribute(name, scope);
250         }
251
252     }
253
254     private Object JavaDoc doGetAttribute(String JavaDoc name, int scope) {
255         switch (scope) {
256         case PAGE_SCOPE:
257             return attributes.get(name);
258
259         case REQUEST_SCOPE:
260             return request.getAttribute(name);
261
262         case SESSION_SCOPE:
263             if (session == null) {
264                 throw new IllegalStateException JavaDoc(Localizer
265                         .getMessage("jsp.error.page.noSession"));
266             }
267             return session.getAttribute(name);
268
269         case APPLICATION_SCOPE:
270             return context.getAttribute(name);
271
272         default:
273             throw new IllegalArgumentException JavaDoc("Invalid scope");
274         }
275     }
276
277     public void setAttribute(final String JavaDoc name, final Object JavaDoc attribute) {
278
279         if (name == null) {
280             throw new NullPointerException JavaDoc(Localizer
281                     .getMessage("jsp.error.attribute.null_name"));
282         }
283
284         if (SecurityUtil.isPackageProtectionEnabled()) {
285             AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
286                 public Object JavaDoc run() {
287                     doSetAttribute(name, attribute);
288                     return null;
289                 }
290             });
291         } else {
292             doSetAttribute(name, attribute);
293         }
294     }
295
296     private void doSetAttribute(String JavaDoc name, Object JavaDoc attribute) {
297         if (attribute != null) {
298             attributes.put(name, attribute);
299         } else {
300             removeAttribute(name, PAGE_SCOPE);
301         }
302     }
303
304     public void setAttribute(final String JavaDoc name, final Object JavaDoc o, final int scope) {
305
306         if (name == null) {
307             throw new NullPointerException JavaDoc(Localizer
308                     .getMessage("jsp.error.attribute.null_name"));
309         }
310
311         if (SecurityUtil.isPackageProtectionEnabled()) {
312             AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
313                 public Object JavaDoc run() {
314                     doSetAttribute(name, o, scope);
315                     return null;
316                 }
317             });
318         } else {
319             doSetAttribute(name, o, scope);
320         }
321
322     }
323
324     private void doSetAttribute(String JavaDoc name, Object JavaDoc o, int scope) {
325         if (o != null) {
326             switch (scope) {
327             case PAGE_SCOPE:
328                 attributes.put(name, o);
329                 break;
330
331             case REQUEST_SCOPE:
332                 request.setAttribute(name, o);
333                 break;
334
335             case SESSION_SCOPE:
336                 if (session == null) {
337                     throw new IllegalStateException JavaDoc(Localizer
338                             .getMessage("jsp.error.page.noSession"));
339                 }
340                 session.setAttribute(name, o);
341                 break;
342
343             case APPLICATION_SCOPE:
344                 context.setAttribute(name, o);
345                 break;
346
347             default:
348                 throw new IllegalArgumentException JavaDoc("Invalid scope");
349             }
350         } else {
351             removeAttribute(name, scope);
352         }
353     }
354
355     public void removeAttribute(final String JavaDoc name, final int scope) {
356
357         if (name == null) {
358             throw new NullPointerException JavaDoc(Localizer
359                     .getMessage("jsp.error.attribute.null_name"));
360         }
361         if (SecurityUtil.isPackageProtectionEnabled()) {
362             AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
363                 public Object JavaDoc run() {
364                     doRemoveAttribute(name, scope);
365                     return null;
366                 }
367             });
368         } else {
369             doRemoveAttribute(name, scope);
370         }
371     }
372
373     private void doRemoveAttribute(String JavaDoc name, int scope) {
374         switch (scope) {
375         case PAGE_SCOPE:
376             attributes.remove(name);
377             break;
378
379         case REQUEST_SCOPE:
380             request.removeAttribute(name);
381             break;
382
383         case SESSION_SCOPE:
384             if (session == null) {
385                 throw new IllegalStateException JavaDoc(Localizer
386                         .getMessage("jsp.error.page.noSession"));
387             }
388             session.removeAttribute(name);
389             break;
390
391         case APPLICATION_SCOPE:
392             context.removeAttribute(name);
393             break;
394
395         default:
396             throw new IllegalArgumentException JavaDoc("Invalid scope");
397         }
398     }
399
400     public int getAttributesScope(final String JavaDoc name) {
401
402         if (name == null) {
403             throw new NullPointerException JavaDoc(Localizer
404                     .getMessage("jsp.error.attribute.null_name"));
405         }
406
407         if (SecurityUtil.isPackageProtectionEnabled()) {
408             return ((Integer JavaDoc) AccessController
409                     .doPrivileged(new PrivilegedAction JavaDoc() {
410                         public Object JavaDoc run() {
411                             return new Integer JavaDoc(doGetAttributeScope(name));
412                         }
413                     })).intValue();
414         } else {
415             return doGetAttributeScope(name);
416         }
417     }
418
419     private int doGetAttributeScope(String JavaDoc name) {
420         if (attributes.get(name) != null)
421             return PAGE_SCOPE;
422
423         if (request.getAttribute(name) != null)
424             return REQUEST_SCOPE;
425
426         if (session != null) {
427             if (session.getAttribute(name) != null)
428                 return SESSION_SCOPE;
429         }
430
431         if (context.getAttribute(name) != null)
432             return APPLICATION_SCOPE;
433
434         return 0;
435     }
436
437     public Object JavaDoc findAttribute(final String JavaDoc name) {
438         if (SecurityUtil.isPackageProtectionEnabled()) {
439             return AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
440                 public Object JavaDoc run() {
441                     if (name == null) {
442                         throw new NullPointerException JavaDoc(Localizer
443                                 .getMessage("jsp.error.attribute.null_name"));
444                     }
445
446                     return doFindAttribute(name);
447                 }
448             });
449         } else {
450             if (name == null) {
451                 throw new NullPointerException JavaDoc(Localizer
452                         .getMessage("jsp.error.attribute.null_name"));
453             }
454
455             return doFindAttribute(name);
456         }
457     }
458
459     private Object JavaDoc doFindAttribute(String JavaDoc name) {
460
461         Object JavaDoc o = attributes.get(name);
462         if (o != null)
463             return o;
464
465         o = request.getAttribute(name);
466         if (o != null)
467             return o;
468
469         if (session != null) {
470             o = session.getAttribute(name);
471             if (o != null)
472                 return o;
473         }
474
475         return context.getAttribute(name);
476     }
477
478     public Enumeration JavaDoc<String JavaDoc> getAttributeNamesInScope(final int scope) {
479         if (SecurityUtil.isPackageProtectionEnabled()) {
480             return (Enumeration JavaDoc) AccessController
481                     .doPrivileged(new PrivilegedAction JavaDoc() {
482                         public Object JavaDoc run() {
483                             return doGetAttributeNamesInScope(scope);
484                         }
485                     });
486         } else {
487             return doGetAttributeNamesInScope(scope);
488         }
489     }
490
491     private Enumeration JavaDoc doGetAttributeNamesInScope(int scope) {
492         switch (scope) {
493         case PAGE_SCOPE:
494             return new Enumerator(attributes.keySet().iterator());
495
496         case REQUEST_SCOPE:
497             return request.getAttributeNames();
498
499         case SESSION_SCOPE:
500             if (session == null) {
501                 throw new IllegalStateException JavaDoc(Localizer
502                         .getMessage("jsp.error.page.noSession"));
503             }
504             return session.getAttributeNames();
505
506         case APPLICATION_SCOPE:
507             return context.getAttributeNames();
508
509         default:
510             throw new IllegalArgumentException JavaDoc("Invalid scope");
511         }
512     }
513
514     public void removeAttribute(final String JavaDoc name) {
515
516         if (name == null) {
517             throw new NullPointerException JavaDoc(Localizer
518                     .getMessage("jsp.error.attribute.null_name"));
519         }
520
521         if (SecurityUtil.isPackageProtectionEnabled()) {
522             AccessController.doPrivileged(new PrivilegedAction JavaDoc() {
523                 public Object JavaDoc run() {
524                     doRemoveAttribute(name);
525                     return null;
526                 }
527             });
528         } else {
529             doRemoveAttribute(name);
530         }
531     }
532
533     private void doRemoveAttribute(String JavaDoc name) {
534         try {
535             removeAttribute(name, PAGE_SCOPE);
536             removeAttribute(name, REQUEST_SCOPE);
537             if (session != null) {
538                 removeAttribute(name, SESSION_SCOPE);
539             }
540             removeAttribute(name, APPLICATION_SCOPE);
541         } catch (Exception JavaDoc ex) {
542             // we remove as much as we can, and
543
// simply ignore possible exceptions
544
}
545     }
546
547     public JspWriter JavaDoc getOut() {
548         return out;
549     }
550
551     public HttpSession JavaDoc getSession() {
552         return session;
553     }
554
555     public Servlet JavaDoc getServlet() {
556         return servlet;
557     }
558
559     public ServletConfig JavaDoc getServletConfig() {
560         return config;
561     }
562
563     public ServletContext JavaDoc getServletContext() {
564         return config.getServletContext();
565     }
566
567     public ServletRequest JavaDoc getRequest() {
568         return request;
569     }
570
571     public ServletResponse JavaDoc getResponse() {
572         return response;
573     }
574
575     /**
576      * Returns the exception associated with this page context, if any. <p/>
577      * Added wrapping for Throwables to avoid ClassCastException: see Bugzilla
578      * 31171 for details.
579      *
580      * @return The Exception associated with this page context, if any.
581      */

582     public Exception JavaDoc getException() {
583         Throwable JavaDoc t = JspRuntimeLibrary.getThrowable(request);
584
585         // Only wrap if needed
586
if ((t != null) && (!(t instanceof Exception JavaDoc))) {
587             t = new JspException JavaDoc(t);
588         }
589
590         return (Exception JavaDoc) t;
591     }
592
593     public Object JavaDoc getPage() {
594         return servlet;
595     }
596
597     private final String JavaDoc getAbsolutePathRelativeToContext(String JavaDoc relativeUrlPath) {
598         String JavaDoc path = relativeUrlPath;
599
600         if (!path.startsWith("/")) {
601             String JavaDoc uri = (String JavaDoc) request
602                     .getAttribute("javax.servlet.include.servlet_path");
603             if (uri == null)
604                 uri = ((HttpServletRequest JavaDoc) request).getServletPath();
605             String JavaDoc baseURI = uri.substring(0, uri.lastIndexOf('/'));
606             path = baseURI + '/' + path;
607         }
608
609         return path;
610     }
611
612     public void include(String JavaDoc relativeUrlPath) throws ServletException JavaDoc,
613             IOException JavaDoc {
614         JspRuntimeLibrary
615                 .include(request, response, relativeUrlPath, out, true);
616     }
617
618     public void include(final String JavaDoc relativeUrlPath, final boolean flush)
619             throws ServletException JavaDoc, IOException JavaDoc {
620         if (SecurityUtil.isPackageProtectionEnabled()) {
621             try {
622                 AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc() {
623                     public Object JavaDoc run() throws Exception JavaDoc {
624                         doInclude(relativeUrlPath, flush);
625                         return null;
626                     }
627                 });
628             } catch (PrivilegedActionException JavaDoc e) {
629                 Exception JavaDoc ex = e.getException();
630                 if (ex instanceof IOException JavaDoc) {
631                     throw (IOException JavaDoc) ex;
632                 } else {
633                     throw (ServletException JavaDoc) ex;
634                 }
635             }
636         } else {
637             doInclude(relativeUrlPath, flush);
638         }
639     }
640
641     private void doInclude(String JavaDoc relativeUrlPath, boolean flush)
642             throws ServletException JavaDoc, IOException JavaDoc {
643         JspRuntimeLibrary.include(request, response, relativeUrlPath, out,
644                 flush);
645     }
646
647     public VariableResolver JavaDoc getVariableResolver() {
648         return new VariableResolverImpl(this.getELContext());
649     }
650
651     public void forward(final String JavaDoc relativeUrlPath) throws ServletException JavaDoc,
652             IOException JavaDoc {
653         if (SecurityUtil.isPackageProtectionEnabled()) {
654             try {
655                 AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc() {
656                     public Object JavaDoc run() throws Exception JavaDoc {
657                         doForward(relativeUrlPath);
658                         return null;
659                     }
660                 });
661             } catch (PrivilegedActionException JavaDoc e) {
662                 Exception JavaDoc ex = e.getException();
663                 if (ex instanceof IOException JavaDoc) {
664                     throw (IOException JavaDoc) ex;
665                 } else {
666                     throw (ServletException JavaDoc) ex;
667                 }
668             }
669         } else {
670             doForward(relativeUrlPath);
671         }
672     }
673
674     private void doForward(String JavaDoc relativeUrlPath) throws ServletException JavaDoc,
675             IOException JavaDoc {
676
677         // JSP.4.5 If the buffer was flushed, throw IllegalStateException
678
try {
679             out.clear();
680         } catch (IOException JavaDoc ex) {
681             IllegalStateException JavaDoc ise = new IllegalStateException JavaDoc(Localizer
682                     .getMessage("jsp.error.attempt_to_clear_flushed_buffer"));
683             ise.initCause(ex);
684             throw ise;
685         }
686
687         // Make sure that the response object is not the wrapper for include
688
while (response instanceof ServletResponseWrapperInclude) {
689             response = ((ServletResponseWrapperInclude) response).getResponse();
690         }
691
692         final String JavaDoc path = getAbsolutePathRelativeToContext(relativeUrlPath);
693         String JavaDoc includeUri = (String JavaDoc) request
694                 .getAttribute(Constants.INC_SERVLET_PATH);
695
696         if (includeUri != null)
697             request.removeAttribute(Constants.INC_SERVLET_PATH);
698         try {
699             context.getRequestDispatcher(path).forward(request, response);
700         } finally {
701             if (includeUri != null)
702                 request.setAttribute(Constants.INC_SERVLET_PATH, includeUri);
703         }
704     }
705
706     public BodyContent JavaDoc pushBody() {
707         return (BodyContent JavaDoc) pushBody(null);
708     }
709
710     public JspWriter JavaDoc pushBody(Writer JavaDoc writer) {
711         depth++;
712         if (depth >= outs.length) {
713             BodyContentImpl[] newOuts = new BodyContentImpl[depth + 1];
714             for (int i = 0; i < outs.length; i++) {
715                 newOuts[i] = outs[i];
716             }
717             newOuts[depth] = new BodyContentImpl(out);
718             outs = newOuts;
719         }
720
721         outs[depth].setWriter(writer);
722         out = outs[depth];
723
724         // Update the value of the "out" attribute in the page scope
725
// attribute namespace of this PageContext
726
setAttribute(OUT, out);
727
728         return outs[depth];
729     }
730
731     public JspWriter JavaDoc popBody() {
732         depth--;
733         if (depth >= 0) {
734             out = outs[depth];
735         } else {
736             out = baseOut;
737         }
738
739         // Update the value of the "out" attribute in the page scope
740
// attribute namespace of this PageContext
741
setAttribute(OUT, out);
742
743         return out;
744     }
745
746     /**
747      * Provides programmatic access to the ExpressionEvaluator. The JSP
748      * Container must return a valid instance of an ExpressionEvaluator that can
749      * parse EL expressions.
750      */

751     public ExpressionEvaluator JavaDoc getExpressionEvaluator() {
752         return new ExpressionEvaluatorImpl(this.applicationContext.getExpressionFactory());
753     }
754
755     public void handlePageException(Exception JavaDoc ex) throws IOException JavaDoc,
756             ServletException JavaDoc {
757         // Should never be called since handleException() called with a
758
// Throwable in the generated servlet.
759
handlePageException((Throwable JavaDoc) ex);
760     }
761
762     public void handlePageException(final Throwable JavaDoc t) throws IOException JavaDoc,
763             ServletException JavaDoc {
764         if (t == null)
765             throw new NullPointerException JavaDoc("null Throwable");
766
767         if (SecurityUtil.isPackageProtectionEnabled()) {
768             try {
769                 AccessController.doPrivileged(new PrivilegedExceptionAction JavaDoc() {
770                     public Object JavaDoc run() throws Exception JavaDoc {
771                         doHandlePageException(t);
772                         return null;
773                     }
774                 });
775             } catch (PrivilegedActionException JavaDoc e) {
776                 Exception JavaDoc ex = e.getException();
777                 if (ex instanceof IOException JavaDoc) {
778                     throw (IOException JavaDoc) ex;
779                 } else {
780                     throw (ServletException JavaDoc) ex;
781                 }
782             }
783         } else {
784             doHandlePageException(t);
785         }
786
787     }
788
789     private void doHandlePageException(Throwable JavaDoc t) throws IOException JavaDoc,
790             ServletException JavaDoc {
791
792         if (errorPageURL != null && !errorPageURL.equals("")) {
793
794             /*
795              * Set request attributes. Do not set the
796              * javax.servlet.error.exception attribute here (instead, set in the
797              * generated servlet code for the error page) in order to prevent
798              * the ErrorReportValve, which is invoked as part of forwarding the
799              * request to the error page, from throwing it if the response has
800              * not been committed (the response will have been committed if the
801              * error page is a JSP page).
802              */

803             request.setAttribute("javax.servlet.jsp.jspException", t);
804             request.setAttribute("javax.servlet.error.status_code",
805                     new Integer JavaDoc(HttpServletResponse.SC_INTERNAL_SERVER_ERROR));
806             request.setAttribute("javax.servlet.error.request_uri",
807                     ((HttpServletRequest JavaDoc) request).getRequestURI());
808             request.setAttribute("javax.servlet.error.servlet_name", config
809                     .getServletName());
810             try {
811                 forward(errorPageURL);
812             } catch (IllegalStateException JavaDoc ise) {
813                 include(errorPageURL);
814             }
815
816             // The error page could be inside an include.
817

818             Object JavaDoc newException = request
819                     .getAttribute("javax.servlet.error.exception");
820
821             // t==null means the attribute was not set.
822
if ((newException != null) && (newException == t)) {
823                 request.removeAttribute("javax.servlet.error.exception");
824             }
825
826             // now clear the error code - to prevent double handling.
827
request.removeAttribute("javax.servlet.error.status_code");
828             request.removeAttribute("javax.servlet.error.request_uri");
829             request.removeAttribute("javax.servlet.error.status_code");
830             request.removeAttribute("javax.servlet.jsp.jspException");
831
832         } else {
833             // Otherwise throw the exception wrapped inside a ServletException.
834
// Set the exception as the root cause in the ServletException
835
// to get a stack trace for the real problem
836
if (t instanceof IOException JavaDoc)
837                 throw (IOException JavaDoc) t;
838             if (t instanceof ServletException JavaDoc)
839                 throw (ServletException JavaDoc) t;
840             if (t instanceof RuntimeException JavaDoc)
841                 throw (RuntimeException JavaDoc) t;
842
843             Throwable JavaDoc rootCause = null;
844             if (t instanceof JspException JavaDoc) {
845                 rootCause = ((JspException JavaDoc) t).getRootCause();
846             } else if (t instanceof ELException JavaDoc) {
847                 rootCause = ((ELException JavaDoc) t).getRootCause();
848             }
849
850             if (rootCause != null) {
851                 throw new ServletException JavaDoc(t.getClass().getName() + ": "
852                         + t.getMessage(), rootCause);
853             }
854
855             throw new ServletException JavaDoc(t);
856         }
857     }
858
859     private static String JavaDoc XmlEscape(String JavaDoc s) {
860         if (s == null)
861             return null;
862         StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
863         for (int i = 0; i < s.length(); i++) {
864             char c = s.charAt(i);
865             if (c == '<') {
866                 sb.append("&lt;");
867             } else if (c == '>') {
868                 sb.append("&gt;");
869             } else if (c == '\'') {
870                 sb.append("&#039;"); // &apos;
871
} else if (c == '&') {
872                 sb.append("&amp;");
873             } else if (c == '"') {
874                 sb.append("&#034;"); // &quot;
875
} else {
876                 sb.append(c);
877             }
878         }
879         return sb.toString();
880     }
881
882     /**
883      * Proprietary method to evaluate EL expressions. XXX - This method should
884      * go away once the EL interpreter moves out of JSTL and into its own
885      * project. For now, this is necessary because the standard machinery is too
886      * slow.
887      *
888      * @param expression
889      * The expression to be evaluated
890      * @param expectedType
891      * The expected resulting type
892      * @param pageContext
893      * The page context
894      * @param functionMap
895      * Maps prefix and name to Method
896      * @return The result of the evaluation
897      */

898     public static Object JavaDoc proprietaryEvaluate(final String JavaDoc expression,
899             final Class JavaDoc expectedType, final PageContext JavaDoc pageContext,
900             final ProtectedFunctionMapper functionMap, final boolean escape)
901             throws ELException JavaDoc {
902         Object JavaDoc retValue;
903         final ExpressionFactory exprFactory = JspFactory.getDefaultFactory().getJspApplicationContext(pageContext.getServletContext()).getExpressionFactory();
904         if (SecurityUtil.isPackageProtectionEnabled()) {
905             try {
906                 retValue = AccessController
907                         .doPrivileged(new PrivilegedExceptionAction JavaDoc() {
908
909                             public Object JavaDoc run() throws Exception JavaDoc {
910                                 ELContextImpl ctx = (ELContextImpl) pageContext.getELContext();
911                                 ctx.setFunctionMapper(new FunctionMapperImpl(functionMap));
912                                 ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType);
913                                 return ve.getValue(ctx);
914                             }
915                         });
916             } catch (PrivilegedActionException JavaDoc ex) {
917                 Exception JavaDoc realEx = ex.getException();
918                 if (realEx instanceof ELException JavaDoc) {
919                     throw (ELException JavaDoc) realEx;
920                 } else {
921                     throw new ELException JavaDoc(realEx);
922                 }
923             }
924         } else {
925             ELContextImpl ctx = (ELContextImpl) pageContext.getELContext();
926             ctx.setFunctionMapper(new FunctionMapperImpl(functionMap));
927             ValueExpression ve = exprFactory.createValueExpression(ctx, expression, expectedType);
928             retValue = ve.getValue(ctx);
929         }
930         if (escape && retValue != null) {
931             retValue = XmlEscape(retValue.toString());
932         }
933
934         return retValue;
935     }
936
937     public ELContext getELContext() {
938         if (this.elContext == null) {
939             this.elContext = this.applicationContext.createELContext(this);
940         }
941         return this.elContext;
942     }
943
944 }
945
Popular Tags