KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > caucho > jsp > PageContextImpl


1 /*
2  * Copyright (c) 1998-2006 Caucho Technology -- all rights reserved
3  *
4  * This file is part of Resin(R) Open Source
5  *
6  * Each copy or derived work must preserve the copyright notice and this
7  * notice unmodified.
8  *
9  * Resin Open Source is free software; you can redistribute it and/or modify
10  * it under the terms of the GNU General Public License as published by
11  * the Free Software Foundation; either version 2 of the License, or
12  * (at your option) any later version.
13  *
14  * Resin Open Source is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
17  * of NON-INFRINGEMENT. See the GNU General Public License for more
18  * details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with Resin Open Source; if not, write to the
22  *
23  * Free Software Foundation, Inc.
24  * 59 Temple Place, Suite 330
25  * Boston, MA 02111-1307 USA
26  *
27  * @author Scott Ferguson
28  */

29
30 package com.caucho.jsp;
31
32 import com.caucho.el.EL;
33 import com.caucho.el.ExprEnv;
34 import com.caucho.jsp.cfg.JspPropertyGroup;
35 import com.caucho.jsp.el.ExpressionEvaluatorImpl;
36 import com.caucho.jsp.el.JspApplicationContextImpl;
37 import com.caucho.jsp.el.PageContextELResolver;
38 import com.caucho.jstl.JstlPageContext;
39 import com.caucho.log.Log;
40 import com.caucho.server.connection.AbstractHttpRequest;
41 import com.caucho.server.connection.AbstractResponseStream;
42 import com.caucho.server.connection.CauchoRequest;
43 import com.caucho.server.connection.CauchoResponse;
44 import com.caucho.server.connection.RequestAdapter;
45 import com.caucho.server.connection.ToCharResponseAdapter;
46 import com.caucho.server.webapp.RequestDispatcherImpl;
47 import com.caucho.server.webapp.WebApp;
48 import com.caucho.util.CharBuffer;
49 import com.caucho.util.HashMapImpl;
50 import com.caucho.util.L10N;
51 import com.caucho.util.NullEnumeration;
52 import com.caucho.vfs.ClientDisconnectException;
53 import com.caucho.vfs.FlushBuffer;
54 import com.caucho.vfs.Path;
55 import com.caucho.vfs.TempCharBuffer;
56 import com.caucho.xpath.VarEnv;
57
58 import org.w3c.dom.Node JavaDoc;
59
60 import javax.el.ELContext;
61 import javax.el.ELContextEvent;
62 import javax.el.ELContextListener;
63 import javax.el.ELResolver;
64 import javax.el.ValueExpression;
65 import javax.servlet.*;
66 import javax.servlet.http.Cookie JavaDoc;
67 import javax.servlet.http.HttpServletRequest JavaDoc;
68 import javax.servlet.http.HttpServletResponse JavaDoc;
69 import javax.servlet.http.HttpSession JavaDoc;
70 import javax.servlet.jsp.ErrorData JavaDoc;
71 import javax.servlet.jsp.JspContext JavaDoc;
72 import javax.servlet.jsp.JspException JavaDoc;
73 import javax.servlet.jsp.JspWriter JavaDoc;
74 import javax.servlet.jsp.PageContext JavaDoc;
75 import javax.servlet.jsp.SkipPageException JavaDoc;
76 import javax.servlet.jsp.el.ExpressionEvaluator JavaDoc;
77 import javax.servlet.jsp.el.VariableResolver JavaDoc;
78 import javax.servlet.jsp.jstl.core.Config;
79 import javax.servlet.jsp.jstl.fmt.LocalizationContext;
80 import javax.servlet.jsp.tagext.BodyContent JavaDoc;
81 import javax.servlet.jsp.tagext.JspFragment JavaDoc;
82 import java.io.FileNotFoundException JavaDoc;
83 import java.io.IOException JavaDoc;
84 import java.io.PrintWriter JavaDoc;
85 import java.io.Reader JavaDoc;
86 import java.io.Writer JavaDoc;
87 import java.lang.reflect.Method JavaDoc;
88 import java.text.MessageFormat JavaDoc;
89 import java.util.Collections JavaDoc;
90 import java.util.Enumeration JavaDoc;
91 import java.util.HashMap JavaDoc;
92 import java.util.Locale JavaDoc;
93 import java.util.Map JavaDoc;
94 import java.util.ResourceBundle JavaDoc;
95 import java.util.logging.Level JavaDoc;
96 import java.util.logging.Logger JavaDoc;
97
98 public class PageContextImpl extends PageContext
99   implements ExprEnv, JstlPageContext, VariableResolver JavaDoc {
100   private static final Logger JavaDoc log = Log.open(PageContextImpl.class);
101   static final L10N L = new L10N(PageContextImpl.class);
102   
103   private JspWriterAdapter _jspAdapter = new JspWriterAdapter();
104   private JspServletOutputStream _jspOutputStream =
105     new JspServletOutputStream(this);
106
107   private Map JavaDoc<String JavaDoc,Object JavaDoc> _attributes;
108   private Servlet _servlet;
109   private HttpServletRequest JavaDoc _request;
110
111   private CauchoResponse _response;
112   private ToCharResponseAdapter _responseAdapter;
113   
114   private WebApp _webApp;
115   private HttpSession JavaDoc _session;
116   private JspWriter JavaDoc _topOut;
117   private JspWriter JavaDoc _out;
118   private String JavaDoc _errorPage;
119   protected boolean _isFilled;
120   
121   private AbstractResponseStream _responseStream;
122
123   private BodyResponseStream _bodyResponseStream;
124   
125   private JspPrintWriter _jspPrintWriter;
126
127   private int _bufferSize = 8192;
128   private boolean autoFlush;
129   private BodyContentImpl _bodyOut;
130
131   private BundleManager _bundleManager;
132
133   private VarEnv _varEnv;
134   private Node JavaDoc _nodeEnv;
135
136   private final CharBuffer _cb = new CharBuffer();
137
138   private VariableResolver JavaDoc _varResolver;
139   private ELContext _elContext;
140   private ELResolver _elResolver;
141   private javax.el.FunctionMapper _functionMapper;
142   private javax.el.VariableMapper _variableMapper;
143   private boolean _hasException;
144
145   private HashMap JavaDoc<String JavaDoc,Method JavaDoc> _functionMap;
146
147   private ExpressionEvaluatorImpl _expressionEvaluator;
148
149   PageContextImpl()
150   {
151     _attributes = new HashMapImpl<String JavaDoc,Object JavaDoc>();
152     
153     _bodyResponseStream = new BodyResponseStream();
154     _bodyResponseStream.start();
155     
156     _jspPrintWriter = new JspPrintWriter();
157   }
158
159   public void initialize(Servlet servlet,
160              ServletRequest JavaDoc request,
161              ServletResponse JavaDoc response,
162              String JavaDoc errorPage,
163              boolean needsSession,
164              int bufferSize,
165              boolean autoFlush)
166   {
167     HttpSession JavaDoc session = null;
168     
169     if (needsSession)
170       session = ((HttpServletRequest JavaDoc) request).getSession(true);
171
172     ServletConfig config = servlet.getServletConfig();
173     WebApp app = (WebApp) config.getServletContext();
174
175     initialize(servlet, app, request, response,
176            errorPage, session, bufferSize, autoFlush,
177            false);
178   }
179
180   public void initialize(Servlet servlet,
181              WebApp app,
182              ServletRequest JavaDoc request,
183              ServletResponse JavaDoc response,
184              String JavaDoc errorPage,
185              HttpSession JavaDoc session,
186              int bufferSize,
187              boolean autoFlush,
188              boolean isPrintNullAsBlank)
189   {
190     _servlet = servlet;
191     _request = (HttpServletRequest JavaDoc) request;
192
193     if (response instanceof CauchoResponse
194     && bufferSize <= TempCharBuffer.SIZE) {
195       _response = (CauchoResponse) response;
196       _responseAdapter = null;
197     }
198     else {
199       // JSP.12.2.3 - JSP must use PrintWriter
200
_responseAdapter = ToCharResponseAdapter.create((HttpServletResponse JavaDoc) response);
201       _response = _responseAdapter;
202     }
203     
204     _responseStream = _response.getResponseStream();
205     _topOut = _jspAdapter;
206     _responseStream.setAutoFlush(autoFlush);
207     _jspAdapter.init(null, _responseStream);
208     _jspAdapter.setPrintNullAsBlank(isPrintNullAsBlank);
209
210     if (bufferSize != TempCharBuffer.SIZE) {
211       try {
212     _responseStream.setBufferSize(bufferSize);
213       } catch (Throwable JavaDoc e) {
214     log.log(Level.FINE, e.toString(), e);
215       }
216     }
217
218     // needed for includes from static pages
219

220     _bufferSize = bufferSize;
221     this.autoFlush = autoFlush;
222     _session = session;
223
224     _out = _topOut;
225     
226     _errorPage = errorPage;
227     _webApp = app;
228
229     //_topOut.init(this, bufferSize, autoFlush);
230

231     // jsp/17ee
232
//_jspPrintWriter.init(_topOut);
233
//_response.setPrintWriter(_jspPrintWriter);
234

235     // not quite correct
236
// _writerStreamImpl.setWriter(_topOut);
237
// _response.setPrintWriter(body.getWriter());
238

239     /*
240     _elContext = null;
241     _elResolver = null;
242     */

243
244     _hasException = false;
245     //if (_attributes.size() > 0)
246
// _attributes.clear();
247
_isFilled = false;
248     _bundleManager = null;
249     _varResolver = null;
250     _nodeEnv = null;
251
252     if (servlet instanceof Page) {
253       Page page = (Page) servlet;
254
255       _functionMap = page._caucho_getFunctionMap();
256     }
257     else
258       _functionMap = null;
259   }
260
261   protected void setOut(JspWriter JavaDoc out)
262   {
263     _out = out;
264   }
265
266   protected void clearAttributes()
267   {
268     _attributes.clear();
269   }
270
271   /**
272    * Returns the page attribute with the given name.
273    *
274    * @param name the attribute name.
275    *
276    * @return the attribute's value.
277    */

278   public Object JavaDoc getAttribute(String JavaDoc name)
279   {
280     if (name == null)
281       throw new NullPointerException JavaDoc(L.l("getAttribute must have a non-null name"));
282     
283     Object JavaDoc value = _attributes.get(name);
284     if (value != null)
285       return value;
286     else if (! _isFilled) {
287       fillAttribute();
288       value = _attributes.get(name);
289     }
290
291     if (value != null) {
292     }
293     else if (name.equals(OUT)) {
294       // jsp/162d
295
return _out;
296     }
297
298     return value;
299   }
300
301   /**
302    * Sets the page attribute with the given name.
303    *
304    * @param name the attribute name.
305    * @param value the new value
306    */

307   public void setAttribute(String JavaDoc name, Object JavaDoc attribute)
308   {
309     if (name == null)
310       throw new NullPointerException JavaDoc(L.l("setAttribute must have a non-null name"));
311     
312     if (attribute != null)
313       _attributes.put(name, attribute);
314     else
315       _attributes.remove(name);
316   }
317
318   /**
319    * Sets the page attribute with the given name.
320    *
321    * @param name the attribute name.
322    * @param value the new value
323    */

324   public Object JavaDoc putAttribute(String JavaDoc name, Object JavaDoc attribute)
325   {
326     if (name == null)
327       throw new NullPointerException JavaDoc(L.l("putAttribute must have a non-null name"));
328     
329     if (attribute != null)
330       return _attributes.put(name, attribute);
331     else
332       return _attributes.remove(name);
333   }
334
335   /**
336    * Removes a named attribute from the page context.
337    *
338    * @param name the name of the attribute to remove
339    */

340   public void removeAttribute(String JavaDoc name)
341   {
342     if (name == null)
343       throw new NullPointerException JavaDoc(L.l("removeAttribute must have a non-null name"));
344     
345     _attributes.remove(name);
346     // jsp/162b
347
if (_request != null)
348       _request.removeAttribute(name);
349
350     if (_session != null) {
351       try {
352     _session.removeAttribute(name);
353       } catch (IllegalStateException JavaDoc e) {
354     // jsp/162f
355
log.log(Level.FINE, e.toString(), e);
356       }
357     }
358     
359     if (_webApp != null)
360       _webApp.removeAttribute(name);
361   }
362
363   public Enumeration<String JavaDoc> getAttributeNames()
364   {
365     if (! _isFilled)
366       fillAttribute();
367
368     return Collections.enumeration(_attributes.keySet());
369   }
370
371   /**
372    * Fills the predefined page content _attributes with their values.
373    */

374   protected void fillAttribute()
375   {
376     _isFilled = true;
377     _attributes.put(PAGE, _servlet);
378     _attributes.put(PAGECONTEXT, this);
379     _attributes.put(REQUEST, getCauchoRequest());
380     _attributes.put(RESPONSE, getCauchoResponse());
381     if (_servlet != null)
382       _attributes.put(CONFIG, _servlet.getServletConfig());
383     if (getSession() != null)
384       _attributes.put(SESSION, getSession());
385     _attributes.put(APPLICATION, getApplication());
386   }
387
388   public Object JavaDoc getAttribute(String JavaDoc name, int scope)
389   {
390     switch (scope) {
391     case PAGE_SCOPE:
392       return getAttribute(name);
393     case REQUEST_SCOPE:
394       return getCauchoRequest().getAttribute(name);
395     case SESSION_SCOPE:
396       {
397     HttpSession JavaDoc session = getSession();
398     return session != null ? session.getValue(name) : null;
399       }
400     case APPLICATION_SCOPE:
401       return getApplication().getAttribute(name);
402
403     default:
404       throw new IllegalArgumentException JavaDoc();
405     }
406   }
407
408   public void setAttribute(String JavaDoc name, Object JavaDoc value, int scope)
409   {
410     switch (scope) {
411     case PAGE_SCOPE:
412       setAttribute(name, value);
413       break;
414
415     case REQUEST_SCOPE:
416       getCauchoRequest().setAttribute(name, value);
417       break;
418
419     case SESSION_SCOPE:
420       if (getSession() != null)
421         getSession().putValue(name, value);
422       break;
423
424     case APPLICATION_SCOPE:
425       getApplication().setAttribute(name, value);
426       break;
427
428     default:
429       throw new IllegalArgumentException JavaDoc();
430     }
431   }
432
433   public void removeAttribute(String JavaDoc name, int scope)
434   {
435     if (name == null)
436       throw new NullPointerException JavaDoc(L.l("removeAttribute must have a non-null name"));
437     
438     switch (scope) {
439     case PAGE_SCOPE:
440       if (name != null)
441     _attributes.remove(name);
442       break;
443
444     case REQUEST_SCOPE:
445       getCauchoRequest().removeAttribute(name);
446       break;
447
448     case SESSION_SCOPE:
449       if (getSession() != null)
450         getSession().removeValue(name);
451       break;
452
453     case APPLICATION_SCOPE:
454       getApplication().removeAttribute(name);
455       break;
456
457     default:
458       throw new IllegalArgumentException JavaDoc();
459     }
460   }
461
462   public Enumeration getAttributeNames(int scope)
463   {
464     switch (scope) {
465     case PAGE_SCOPE:
466       return getAttributeNames();
467
468     case REQUEST_SCOPE:
469       return getCauchoRequest().getAttributeNames();
470
471     case SESSION_SCOPE:
472       if (getSession() != null)
473         return new StringArrayEnum(getSession().getValueNames());
474       else
475         return NullEnumeration.create();
476
477     case APPLICATION_SCOPE:
478       return getApplication().getAttributeNames();
479
480     default:
481       throw new IllegalArgumentException JavaDoc();
482     }
483   }
484
485   public Enumeration getAttributeNamesInScope(int scope)
486   {
487     return getAttributeNames(scope);
488   }
489
490   /**
491    * Finds an attribute in any of the scopes from page to webApp.
492    *
493    * @param name the attribute name.
494    *
495    * @return the attribute value
496    */

497   public Object JavaDoc findAttribute(String JavaDoc name)
498   {
499     Object JavaDoc value;
500
501     if ((value = getAttribute(name)) != null)
502       return value;
503
504     if ((value = getCauchoRequest().getAttribute(name)) != null)
505       return value;
506
507     HttpSession JavaDoc session = getSession();
508     if (session != null) {
509       try {
510     value = session.getAttribute(name);
511       } catch (IllegalStateException JavaDoc e) {
512     // jsp/162e
513
log.log(Level.FINE, e.toString(), e);
514       }
515
516       if (value != null)
517     return value;
518     }
519
520     return getServletContext().getAttribute(name);
521   }
522
523   /**
524    * Return the scope of the named attribute.
525    *
526    * @param name the name of the attribute.
527    *
528    * @return the scope of the attribute
529    */

530   public int getAttributesScope(String JavaDoc name)
531   {
532     if (getAttribute(name) != null)
533       return PAGE_SCOPE;
534
535     if (getCauchoRequest().getAttribute(name) != null)
536       return REQUEST_SCOPE;
537
538     HttpSession JavaDoc session = getSession();
539     if (session != null && session.getValue(name) != null)
540       return SESSION_SCOPE;
541
542     if (getApplication().getAttribute(name) != null)
543       return APPLICATION_SCOPE;
544
545     return 0;
546   }
547
548   /**
549    * Sets the attribute map.
550    */

551   public Map JavaDoc<String JavaDoc,Object JavaDoc> setMap(Map JavaDoc<String JavaDoc,Object JavaDoc> map)
552   {
553     Map JavaDoc<String JavaDoc,Object JavaDoc> oldMap = _attributes;
554     _attributes = map;
555     return oldMap;
556   }
557
558   /**
559    * Returns the current writer.
560    */

561   public JspWriter JavaDoc getOut()
562   {
563     return _out;
564   }
565
566   /**
567    * Pushes a new BodyContent onto the JspWriter stack.
568    */

569   public BodyContent JavaDoc pushBody()
570   {
571     BodyContentImpl body;
572     if (_bodyOut != null) {
573       body = _bodyOut;
574       _bodyOut = null;
575     }
576     else
577       body = BodyContentImpl.allocate();
578
579     CauchoResponse response = getCauchoResponse();
580     
581     body.init(_out);
582     
583     _out = body;
584
585     response.setForbidForward(true);
586     try {
587       _bodyResponseStream.flushBuffer();
588     } catch (IOException JavaDoc e) {
589     }
590     _bodyResponseStream.start();
591     _bodyResponseStream.setWriter(body);
592     _bodyResponseStream.setEncoding(response.getCharacterEncoding());
593     response.setResponseStream(_bodyResponseStream);
594     
595     return body;
596   }
597
598   /**
599    * Pushes a new writer onto the JspWriter stack.
600    */

601   public JspWriter JavaDoc pushBody(Writer JavaDoc writer)
602   {
603     if (writer == _out)
604       return null;
605     
606     JspWriter JavaDoc oldWriter = _out;
607     
608     StreamJspWriter jspWriter;
609
610     jspWriter = new StreamJspWriter();
611     jspWriter.init(_out, writer);
612     
613     _out = jspWriter;
614
615     getCauchoResponse().setForbidForward(true);
616
617     _bodyResponseStream.setWriter(writer);
618     getCauchoResponse().setResponseStream(_bodyResponseStream);
619
620     return oldWriter;
621   }
622
623   /**
624    * Pops the BodyContent from the JspWriter stack.
625    *
626    * @return the enclosing writer
627    */

628   public JspWriter JavaDoc popBody()
629   {
630     BodyContentImpl bodyOut = (BodyContentImpl) _out;
631     _out = bodyOut.getEnclosingWriter();
632
633     try {
634       _bodyResponseStream.flushBuffer();
635       //if (_writeStream != null)
636
// _writeStream.flushBuffer();
637
} catch (IOException JavaDoc e) {
638       log.log(Level.WARNING, e.toString(), e);
639     }
640     
641     if (_out instanceof StreamJspWriter) {
642       StreamJspWriter writer = (StreamJspWriter) _out;
643
644       _bodyResponseStream.setWriter(writer.getWriter());
645     }
646     else if (_out instanceof JspWriterAdapter) {
647       if (getCauchoResponse() != null) {
648     getCauchoResponse().setResponseStream(_responseStream);
649     getCauchoResponse().setForbidForward(false);
650       }
651     }
652     else if (_out instanceof BodyContentImpl) {
653       BodyContentImpl body = (BodyContentImpl) _out;
654       
655       _bodyResponseStream.setWriter(body.getWriter());
656     }
657
658     return _out;
659   }
660
661   /**
662    * Pops the BodyContent from the JspWriter stack.
663    *
664    * @return the enclosing writer
665    */

666   public JspWriter JavaDoc popAndReleaseBody()
667     throws IOException JavaDoc
668   {
669     BodyContentImpl body = (BodyContentImpl) getOut();
670
671     JspWriter JavaDoc out = popBody();
672
673     releaseBody(body);
674
675     return out;
676   }
677
678   public void releaseBody(BodyContentImpl out)
679     throws IOException JavaDoc
680   {
681     if (_bodyOut == null) {
682       out.releaseNoFree();
683       _bodyOut = out;
684     }
685     else
686       out.release();
687   }
688
689   /**
690    * Pops the BodyContent from the JspWriter stack.
691    *
692    * @param oldWriter the old writer
693    */

694   public JspWriter JavaDoc setWriter(JspWriter JavaDoc oldWriter)
695   {
696     if (_out == oldWriter)
697       return oldWriter;
698
699     /*
700     if (_out instanceof FlushBuffer) {
701       try {
702     ((FlushBuffer) _out).flushBuffer();
703       } catch (IOException e) {
704       }
705     }
706     */

707     try {
708       if (_out instanceof FlushBuffer)
709     ((FlushBuffer) _out).flushBuffer();
710     } catch (IOException JavaDoc e) {
711     }
712     
713     _out = oldWriter;
714
715     // jsp/18eg
716
if (_out instanceof StreamJspWriter) {
717       StreamJspWriter writer = (StreamJspWriter) _out;
718
719       _bodyResponseStream.setWriter(writer.getWriter());
720     }
721     else if (_out instanceof JspWriterAdapter) {
722       if (getCauchoResponse() != null) {
723     getCauchoResponse().setResponseStream(_responseStream);
724     getCauchoResponse().setForbidForward(false);
725       }
726     }
727     else if (_out instanceof BodyContentImpl) {
728       BodyContentImpl body = (BodyContentImpl) _out;
729       
730       _bodyResponseStream.setWriter(body.getWriter());
731     }
732
733     return oldWriter;
734
735     // getCauchoResponse().setWriter(_os);
736
}
737
738   /**
739    * Returns the top writer.
740    */

741   public PrintWriter JavaDoc getTopWriter()
742     throws IOException JavaDoc
743   {
744     CauchoResponse response = getCauchoResponse();
745       
746     AbstractResponseStream currentStream = response.getResponseStream();
747     
748     response.setResponseStream(_responseStream);
749
750     try {
751       return response.getWriter();
752     } finally {
753       response.setResponseStream(currentStream);
754     }
755   }
756
757   /**
758    * Returns the response output stream.
759    */

760   ServletOutputStream getOutputStream()
761   {
762     try {
763       return getCauchoResponse().getOutputStream();
764     } catch (IOException JavaDoc e) {
765       throw new RuntimeException JavaDoc(e);
766     }
767   }
768
769   /**
770    * Returns the underlying servlet for the page.
771    */

772   public Object JavaDoc getPage()
773   {
774     return _servlet;
775   }
776
777   /**
778    * Returns the servlet request for the page.
779    */

780   public ServletRequest JavaDoc getRequest()
781   {
782     return _request;
783   }
784   
785   /**
786    * Returns the servlet response for the page.
787    */

788   public ServletResponse JavaDoc getResponse()
789   {
790     return getCauchoResponse();
791   }
792   
793   /**
794    * Returns the servlet response for the page.
795    */

796   public CauchoResponse getCauchoResponse()
797   {
798     return _response;
799   }
800   
801   /**
802    * Returns the servlet response for the page.
803    */

804   public HttpServletRequest JavaDoc getCauchoRequest()
805   {
806     return _request;
807   }
808
809   public HttpSession JavaDoc getSession()
810   {
811     if (_session == null)
812       _session = getCauchoRequest().getSession(false);
813     
814     return _session;
815   }
816
817   /**
818    * Returns the session, throwing an IllegalStateException if it's
819    * not available.
820    */

821   public HttpSession JavaDoc getSessionScope()
822   {
823     if (_session == null)
824       _session = getCauchoRequest().getSession(false);
825
826     if (_session == null)
827       throw new IllegalStateException JavaDoc(L.l("session is not available"));
828     
829     return _session;
830   }
831
832   public ServletConfig getServletConfig()
833   {
834     return _servlet.getServletConfig();
835   }
836
837   /**
838    * Returns the page's servlet context.
839    */

840   public ServletContext getServletContext()
841   {
842     return _webApp;
843   }
844
845   /**
846    * Returns the page's webApp.
847    */

848   public WebApp getApplication()
849   {
850     return _webApp;
851   }
852
853   /**
854    * Returns the page's error page.
855    */

856   public String JavaDoc getErrorPage()
857   {
858     return _errorPage;
859   }
860
861   /**
862    * Sets the page's error page.
863    */

864   public void setErrorPage(String JavaDoc errorPage)
865   {
866     _errorPage = errorPage;
867   }
868   
869   public Exception JavaDoc getException()
870   {
871     return (Exception JavaDoc) getThrowable();
872   }
873
874   /**
875    * Returns the Throwable stored by the error page.
876    */

877   public Throwable JavaDoc getThrowable()
878   {
879     Throwable JavaDoc exn = (Throwable JavaDoc) getCauchoRequest().getAttribute(EXCEPTION);
880     
881     if (exn == null)
882       exn = (Throwable JavaDoc) getCauchoRequest().getAttribute("javax.servlet.error.exception_type");
883     if (exn == null)
884       exn = (Throwable JavaDoc) getCauchoRequest().getAttribute("javax.servlet.jsp:jspException");
885     
886     return exn;
887   }
888
889   public void include(String JavaDoc relativeUrl)
890     throws ServletException, IOException JavaDoc
891   {
892     include(relativeUrl, false);
893   }
894   
895   /**
896    * Include another servlet into the current output stream.
897    *
898    * @param relativeUrl url relative to the current request.
899    */

900   public void include(String JavaDoc relativeUrl, String JavaDoc query, boolean flush)
901     throws ServletException, IOException JavaDoc
902   {
903     if ("".equals(query)) {
904     }
905     else if (relativeUrl.indexOf('?') > 0)
906       relativeUrl = relativeUrl + '&' + query;
907     else
908       relativeUrl = relativeUrl + '?' + query;
909
910     include(relativeUrl, flush);
911   }
912   
913   /**
914    * Include another servlet into the current output stream.
915    *
916    * @param relativeUrl url relative to the current request.
917    */

918   public void include(String JavaDoc relativeUrl, boolean flush)
919     throws ServletException, IOException JavaDoc
920   {
921     RequestDispatcher rd = null;
922
923     HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) getCauchoRequest();
924     HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc) getResponse();
925
926     if (relativeUrl != null && ! relativeUrl.startsWith("/")) {
927       String JavaDoc path = RequestAdapter.getPageServletPath(req);
928       if (path == null)
929         path = RequestAdapter.getPagePathInfo(req);
930       if (path == null)
931         path = "/";
932       int p = path.lastIndexOf('/');
933       if (p >= 0) {
934     _cb.clear();
935     _cb.append(path, 0, p + 1);
936     _cb.append(relativeUrl);
937         rd = getServletContext().getRequestDispatcher(_cb.toString());
938       }
939     }
940
941     if (rd == null)
942       rd = req.getRequestDispatcher(relativeUrl);
943
944     if (rd == null)
945       throw new ServletException(L.l("unknown including page `{0}'.",
946                                      relativeUrl));
947
948     // the FlushBuffer needs to happen to deal with OpenSymphony (Bug#1710)
949
// jsp/17e9, 15lc, 15m4
950
if (! flush) {
951     }
952     else if (_out instanceof FlushBuffer)
953       ((FlushBuffer) _out).flushBuffer();
954     else if (flush)
955       _out.flush();
956
957     rd.include(req, res);
958   }
959   
960   /**
961    * Include another servlet into the current output stream.
962    *
963    * @param relativeUrl url relative to the current request.
964    */

965   public void forward(String JavaDoc relativeUrl, String JavaDoc query)
966     throws ServletException, IOException JavaDoc
967   {
968     if ("".equals(query)) {
969     }
970     else if (relativeUrl.indexOf('?') > 0)
971       relativeUrl = relativeUrl + '&' + query;
972     else
973       relativeUrl = relativeUrl + '?' + query;
974
975     forward(relativeUrl);
976   }
977
978   /**
979    * Forward a subrequest relative to the current url. Absolute URLs
980    * are relative to the context root.
981    *
982    * @param relativeUrl url relative to the current file
983    */

984   public void forward(String JavaDoc relativeUrl)
985     throws ServletException, IOException JavaDoc
986   {
987     if (_bufferSize == 0) {
988       // jsp/15m3, tck
989
if (_out instanceof FlushBuffer)
990     ((FlushBuffer) _out).flushBuffer();
991       else
992     _out.flush();
993     }
994
995     RequestDispatcher rd = null;
996
997     HttpServletRequest JavaDoc req = (HttpServletRequest JavaDoc) getCauchoRequest();
998     HttpServletResponse JavaDoc res = (HttpServletResponse JavaDoc) getResponse();
999
1000    if (res.isCommitted())
1001      throw new IOException JavaDoc(L.l("can't forward after writing HTTP headers"));
1002    
1003    _out.clear();
1004
1005    if (relativeUrl != null && ! relativeUrl.startsWith("/")) {
1006      String JavaDoc servletPath = RequestAdapter.getPageServletPath(req);
1007      int p = servletPath.lastIndexOf('/');
1008      if (p >= 0) {
1009    _cb.clear();
1010    _cb.append(servletPath, 0, p + 1);
1011    _cb.append(relativeUrl);
1012        rd = getServletContext().getRequestDispatcher(_cb.toString());
1013      }
1014    }
1015
1016    if (rd == null)
1017      rd = req.getRequestDispatcher(relativeUrl);
1018
1019    if (rd == null)
1020      throw new ServletException(L.l("unknown forwarding page: `{0}'",
1021                                     relativeUrl));
1022    rd.forward(req, res);
1023
1024    _out.close();
1025    _responseStream.close();
1026  }
1027
1028  /**
1029   * Handles an exception caught in the JSP page.
1030   *
1031   * @param e the caught exception
1032   */

1033  public void handlePageException(Exception JavaDoc e)
1034    throws ServletException, IOException JavaDoc
1035  {
1036    handlePageException((Throwable JavaDoc) e);
1037  }
1038
1039  /**
1040   * Handles an exception caught in the JSP page.
1041   *
1042   * @param e the caught exception
1043   */

1044  public void handlePageException(Throwable JavaDoc e)
1045    throws ServletException, IOException JavaDoc
1046  {
1047    if (e instanceof SkipPageException JavaDoc)
1048      return;
1049
1050    HttpServletRequest JavaDoc request = getCauchoRequest();
1051    
1052    request.setAttribute("javax.servlet.jsp.jspException", e);
1053
1054    CauchoResponse response = getCauchoResponse();
1055    
1056    response.setForbidForward(false);
1057    response.setResponseStream(_responseStream);
1058    response.killCache();
1059    response.setNoCache(true);
1060
1061    _hasException = true;
1062
1063    if (e instanceof ClientDisconnectException)
1064      throw (ClientDisconnectException) e;
1065
1066    if (! (_servlet instanceof Page)) {
1067    }
1068    else if (getApplication() == null
1069         || getApplication().getJsp() == null
1070         || ! getApplication().getJsp().isRecompileOnError()) {
1071    }
1072    else if (e instanceof OutOfMemoryError JavaDoc) {
1073    }
1074    else if (e instanceof Error JavaDoc) {
1075      try {
1076    Path workDir = getApplication().getAppDir().lookup("WEB-INF/work");
1077    String JavaDoc className = _servlet.getClass().getName();
1078    Path path = workDir.lookup(className.replace('.', '/') + ".class");
1079    
1080    log.warning("Removing " + path + " due to " + e);
1081            
1082    path.remove();
1083      } catch (Exception JavaDoc e1) {
1084      }
1085      Page page = (Page) _servlet;
1086
1087      page._caucho_unload();
1088      if (! page.isDead()) {
1089    page.setDead();
1090    page.destroy();
1091      }
1092    }
1093
1094    _topOut.clearBuffer();
1095    
1096    if (_errorPage != null) {
1097      getApplication().log(e.toString(), e);
1098
1099      getCauchoRequest().setAttribute(EXCEPTION, e);
1100      getCauchoRequest().setAttribute("javax.servlet.error.exception", e);
1101      getCauchoRequest().setAttribute("javax.servlet.error.exception_type", e);
1102      getCauchoRequest().setAttribute("javax.servlet.error.request_uri",
1103                            getCauchoRequest().getRequestURI());
1104
1105      try {
1106    RequestDispatcher rd = getCauchoRequest().getRequestDispatcher(_errorPage);
1107
1108        if (rd instanceof RequestDispatcherImpl) {
1109      getCauchoResponse().setHasError(true);
1110      
1111          ((RequestDispatcherImpl) rd).error(getCauchoRequest(), getCauchoResponse());
1112        }
1113        else {
1114      if (rd != null) {
1115        getCauchoResponse().killCache();
1116        getCauchoResponse().setNoCache(true);
1117        rd.forward(getCauchoRequest(), getCauchoResponse());
1118      }
1119      else {
1120        log.log(Level.FINE, e.toString(), e);
1121        throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.",
1122                       _errorPage));
1123      }
1124        }
1125        
1126      } catch (FileNotFoundException JavaDoc e2) {
1127        log.log(Level.WARNING, e.toString(), e2);
1128        throw new ServletException(L.l("`{0}' is an unknown error page. The JSP errorPage directive must refer to a valid URL relative to the current web-app.",
1129                                       _errorPage));
1130      } catch (IOException JavaDoc e2) {
1131        log.log(Level.FINE, e.toString(), e2);
1132      }
1133
1134      return;
1135    }
1136
1137    /*
1138    if (_servlet instanceof Page && ! (e instanceof LineMapException)) {
1139      LineMap lineMap = ((Page) _servlet)._caucho_getLineMap();
1140      
1141      if (lineMap != null)
1142        e = new JspLineException(e, lineMap);
1143    }
1144    */

1145    
1146    if (e instanceof ServletException) {
1147      throw (ServletException) e;
1148    }
1149    else if (e instanceof IOException JavaDoc) {
1150      throw (IOException JavaDoc) e;
1151    }
1152    else if (e instanceof RuntimeException JavaDoc) {
1153      throw (RuntimeException JavaDoc) e;
1154    }
1155    else if (e instanceof Error JavaDoc) {
1156      throw (Error JavaDoc) e;
1157    }
1158    else {
1159      throw new ServletException(e);
1160    }
1161  }
1162
1163  /**
1164   * Returns the error data
1165   */

1166  public ErrorData JavaDoc getErrorData()
1167  {
1168    String JavaDoc uri = (String JavaDoc) getCauchoRequest().getAttribute(AbstractHttpRequest.ERROR_URI);
1169
1170    if (uri == null)
1171      return null;
1172
1173    Integer JavaDoc status = (Integer JavaDoc) getCauchoRequest().getAttribute(AbstractHttpRequest.STATUS_CODE);
1174
1175    return new ErrorData JavaDoc(getThrowable(),
1176             status == null ? 0 : status.intValue(),
1177             (String JavaDoc) getCauchoRequest().getAttribute(AbstractHttpRequest.ERROR_URI),
1178             (String JavaDoc) getCauchoRequest().getAttribute(AbstractHttpRequest.SERVLET_NAME));
1179  }
1180
1181  /**
1182   * Returns the variable resolver
1183   */

1184  public javax.servlet.jsp.el.VariableResolver JavaDoc getVariableResolver()
1185  {
1186    return this;
1187  }
1188
1189  /**
1190   * Returns the expression evaluator
1191   */

1192  public ExpressionEvaluator JavaDoc getExpressionEvaluator()
1193  {
1194    if (_expressionEvaluator == null)
1195      _expressionEvaluator = new ExpressionEvaluatorImpl(getELContext());
1196    
1197    return _expressionEvaluator;
1198  }
1199
1200  /**
1201   * Returns the expression evaluator
1202   */

1203  public ELContext getELContext()
1204  {
1205    if (_elContext == null) {
1206      _elContext = new PageELContext();
1207
1208      WebApp webApp = getApplication();
1209      
1210      JspApplicationContextImpl jspContext
1211    = (JspApplicationContextImpl) webApp.getJspApplicationContext();
1212
1213      ELResolver []resolverArray = jspContext.getELResolverArray();
1214      
1215      _elResolver = new PageContextELResolver(this, resolverArray);
1216
1217      ELContextListener []listenerArray = jspContext.getELListenerArray();
1218
1219      if (listenerArray.length > 0) {
1220    ELContextEvent event = new ELContextEvent(_elContext);
1221
1222    for (int i = 0; i < listenerArray.length; i++) {
1223      listenerArray[i].contextCreated(event);
1224    }
1225      }
1226      
1227      _functionMapper = new PageFunctionMapper();
1228      _variableMapper = new PageVariableMapper();
1229    }
1230    
1231    return _elContext;
1232  }
1233
1234  /**
1235   * Given a relative url, return the absolute url.
1236   *
1237   * @param value the relative url
1238   *
1239   * @return the absolute url.
1240   */

1241  private String JavaDoc getRelativeUrl(String JavaDoc value)
1242  {
1243    if (value.length() > 0 && value.charAt(0) == '/')
1244      return value;
1245
1246    ServletContext context = getServletContext();
1247    String JavaDoc contextPath = RequestAdapter.getPageContextPath(getCauchoRequest());
1248    String JavaDoc uri = RequestAdapter.getPageURI(getCauchoRequest());
1249    String JavaDoc relPath = uri.substring(contextPath.length());
1250
1251    int p = relPath.lastIndexOf('/');
1252    String JavaDoc urlPwd = p <= 0 ? "/" : relPath.substring(0, p + 1);
1253    
1254    return urlPwd + value;
1255  }
1256
1257  /**
1258   * Releases the context.
1259   */

1260  public void release()
1261  {
1262    try {
1263      _servlet = null;
1264      
1265      if (_attributes.size() > 0)
1266    _attributes.clear();
1267
1268      /* XXX:
1269      if (! autoFlush && response instanceof Response)
1270        ((Response) response).setDisableAutoFlush(false);
1271      */

1272
1273      getCauchoResponse().setResponseStream(_responseStream);
1274      getCauchoResponse().setFlushBuffer(null);
1275
1276      _request = null;
1277      _webApp = null;
1278      _session = null;
1279      while (_out instanceof AbstractJspWriter) {
1280    if (_out instanceof AbstractJspWriter)
1281      _out = ((AbstractJspWriter) _out).popWriter();
1282      }
1283
1284      JspWriter JavaDoc out = _out;
1285      _out = null;
1286      _topOut = null;
1287      _nodeEnv = null;
1288      _jspOutputStream.release();
1289      AbstractResponseStream responseStream = _responseStream;
1290      _responseStream = null;
1291
1292      if (_responseAdapter != null) {
1293        // jsp/15l3
1294
_responseAdapter.finish();
1295    // _responseAdapter.close();
1296
ToCharResponseAdapter resAdapt = _responseAdapter;
1297    ToCharResponseAdapter.free(resAdapt);
1298      }
1299
1300      /*
1301    // server/137q
1302      if (! _hasException && responseStream != null)
1303        responseStream.close();
1304      */

1305    
1306      _response = null;
1307    } catch (IOException JavaDoc e) {
1308      _out = null;
1309    }
1310  }
1311  
1312  /**
1313   * Returns the localized message appropriate for the current context.
1314   */

1315  public String JavaDoc getLocalizedMessage(String JavaDoc key,
1316                                    Object JavaDoc []args,
1317                                    String JavaDoc basename)
1318  {
1319    Object JavaDoc lc = getAttribute("caucho.bundle");
1320    if (lc == null)
1321      lc = Config.find(this, Config.FMT_LOCALIZATION_CONTEXT);
1322    
1323    return getLocalizedMessage(lc, key, args, basename);
1324  }
1325
1326  /**
1327   * Returns the localized message appropriate for the current context.
1328   */

1329  public String JavaDoc getLocalizedMessage(Object JavaDoc lc,
1330                                    String JavaDoc key,
1331                                    Object JavaDoc []args,
1332                                    String JavaDoc basename)
1333  {
1334    String JavaDoc bundleString = null;
1335
1336    // jsp/1c51, jsp/1c54
1337
String JavaDoc prefix = (String JavaDoc) getAttribute("caucho.bundle.prefix");
1338
1339    if (prefix != null)
1340      key = prefix + key;
1341
1342    if (lc == null) {
1343      lc = getAttribute("caucho.bundle");
1344      if (lc == null)
1345        lc = Config.find(this, Config.FMT_LOCALIZATION_CONTEXT);
1346    }
1347
1348    Locale JavaDoc locale = null;
1349
1350    if (lc instanceof LocalizationContext) {
1351      ResourceBundle JavaDoc bundle = ((LocalizationContext) lc).getResourceBundle();
1352      locale = ((LocalizationContext) lc).getLocale();
1353
1354      try {
1355        if (bundle != null)
1356          bundleString = bundle.getString(key);
1357      } catch (Exception JavaDoc e) {
1358      }
1359    }
1360    else if (lc instanceof String JavaDoc) {
1361      LocalizationContext loc = getBundle((String JavaDoc) lc);
1362      locale = loc.getLocale();
1363      
1364      ResourceBundle JavaDoc bundle = loc.getResourceBundle();
1365      
1366      try {
1367        if (bundle != null)
1368          bundleString = bundle.getString(key);
1369      } catch (Exception JavaDoc e) {
1370      }
1371    }
1372
1373    if (bundleString == null)
1374      return "???" + key + "???";
1375    else if (args == null || args.length == 0)
1376      return bundleString;
1377
1378    if (locale == null)
1379      locale = getLocale();
1380
1381    if (locale != null)
1382      return new MessageFormat JavaDoc(bundleString, locale).format(args);
1383    else
1384      return new MessageFormat JavaDoc(bundleString).format(args);
1385  }
1386
1387  /**
1388   * Returns the localized message appropriate for the current context.
1389   */

1390  public LocalizationContext getBundle(String JavaDoc name)
1391  {
1392    Object JavaDoc localeObj = Config.find(this, Config.FMT_LOCALE);
1393    LocalizationContext bundle = null;
1394    BundleManager manager = getBundleManager();
1395
1396    if (localeObj instanceof Locale JavaDoc) {
1397      Locale JavaDoc locale = (Locale JavaDoc) localeObj;
1398
1399      bundle = manager.getBundle(name, locale);
1400    }
1401    else if (localeObj instanceof String JavaDoc) {
1402      Locale JavaDoc locale = getLocale((String JavaDoc) localeObj, null);
1403
1404      bundle = manager.getBundle(name, locale);
1405    }
1406    else {
1407      String JavaDoc acceptLanguage = getCauchoRequest().getHeader("Accept-Language");
1408
1409      if (acceptLanguage != null) {
1410    String JavaDoc cacheKey = name + acceptLanguage;
1411    bundle = manager.getBundle(name, cacheKey, getCauchoRequest().getLocales());
1412      }
1413    }
1414
1415    if (bundle != null)
1416      return bundle;
1417
1418    Object JavaDoc fallback = Config.find(this, Config.FMT_FALLBACK_LOCALE);
1419
1420    if (fallback instanceof Locale JavaDoc) {
1421      Locale JavaDoc locale = (Locale JavaDoc) fallback;
1422
1423      bundle = manager.getBundle(name, locale);
1424    }
1425    else if (fallback instanceof String JavaDoc) {
1426      String JavaDoc localeName = (String JavaDoc) fallback;
1427      Locale JavaDoc locale = getLocale(localeName, null);
1428
1429      bundle = manager.getBundle(name, locale);
1430    }
1431
1432    if (bundle != null)
1433      return bundle;
1434    
1435    bundle = manager.getBundle(name);
1436
1437    if (bundle != null)
1438      return bundle;
1439    else
1440      return BundleManager.NULL_BUNDLE;
1441  }
1442
1443  /**
1444   * Returns the currently active locale.
1445   */

1446  public Locale JavaDoc getLocale()
1447  {
1448    Object JavaDoc localeObj = Config.find(this, Config.FMT_LOCALE);
1449
1450    if (localeObj instanceof Locale JavaDoc)
1451      return (Locale JavaDoc) localeObj;
1452    else if (localeObj instanceof String JavaDoc)
1453      return getLocale((String JavaDoc) localeObj, null);
1454
1455    LocalizationContext lc;
1456    lc = (LocalizationContext) getAttribute("caucho.bundle");
1457
1458    Locale JavaDoc locale = null;
1459    if (lc != null)
1460      locale = lc.getLocale();
1461
1462    if (locale != null)
1463      return locale;
1464    
1465    String JavaDoc acceptLanguage = getCauchoRequest().getHeader("Accept-Language");
1466
1467    if (acceptLanguage != null) {
1468      Enumeration e = getCauchoRequest().getLocales();
1469
1470      if (e != null && e.hasMoreElements())
1471    locale = (Locale JavaDoc) e.nextElement();
1472    }
1473    
1474    return locale;
1475  }
1476
1477  public static Locale JavaDoc getLocale(String JavaDoc value, String JavaDoc variant)
1478  {
1479    Locale JavaDoc locale = null;
1480    int len = value.length();
1481    
1482    CharBuffer cb = new CharBuffer();
1483    int i = 0;
1484    char ch = 0;
1485    for (; i < len && (ch = value.charAt(i)) != '_' && ch != '-'; i++)
1486      cb.append(ch);
1487
1488    String JavaDoc language = cb.toString();
1489
1490    if (ch == '_' || ch == '-') {
1491      cb.clear();
1492
1493      for (i++; i < len && (ch = value.charAt(i)) != '_' && ch != '-'; i++)
1494        cb.append(ch);
1495
1496      String JavaDoc country = cb.toString();
1497
1498      if (variant != null && ! variant.equals(""))
1499    return new Locale JavaDoc(language, country, variant);
1500      else
1501    return new Locale JavaDoc(language, country);
1502    }
1503    else if (variant != null && ! variant.equals(""))
1504      return new Locale JavaDoc(language, "", variant);
1505    else
1506      return new Locale JavaDoc(language, "");
1507  }
1508
1509
1510  public static void printBody(BodyContentImpl body, boolean isEscaped)
1511    throws IOException JavaDoc
1512  {
1513    JspWriter JavaDoc out = body.getEnclosingWriter();
1514    CharBuffer string = body.getCharBuffer();
1515    char []cBuf = string.getBuffer();
1516
1517    int length = string.length() - 1;
1518
1519    for (; length >= 0; length--) {
1520      char ch = cBuf[length];
1521      if (ch != ' ' && ch != '\n' && ch != '\t' && ch != '\r')
1522        break;
1523    }
1524    length++;
1525
1526    int i;
1527
1528    for (i = 0; i < length; i++) {
1529      char ch = cBuf[i];
1530      if (ch != ' ' && ch != '\n' && ch != '\t' && ch != '\r')
1531        break;
1532    }
1533
1534    if (! isEscaped) {
1535      out.write(cBuf, i, length - i);
1536      return;
1537    }
1538
1539    for (; i < length; i++) {
1540      char ch = cBuf[i];
1541
1542      switch (ch) {
1543      case '<':
1544        out.write("&lt;");
1545        break;
1546      case '>':
1547        out.write("&gt;");
1548        break;
1549      case '&':
1550        out.write("&amp;");
1551        break;
1552      case '\'':
1553        out.write("&#039;");
1554        break;
1555      case '"':
1556        out.write("&#034;");
1557        break;
1558      default:
1559        out.write((char) ch);
1560        break;
1561      }
1562    }
1563  }
1564
1565  /**
1566   * Evaluates the fragment, returing the string value.
1567   */

1568  public String JavaDoc invoke(JspFragment JavaDoc fragment)
1569    throws JspException JavaDoc, IOException JavaDoc
1570  {
1571    if (fragment == null)
1572      return "";
1573    
1574    BodyContentImpl body = (BodyContentImpl) pushBody();
1575
1576    try {
1577      fragment.invoke(body);
1578      return body.getString();
1579    } finally {
1580      popBody();
1581      body.release();
1582    }
1583  }
1584
1585  /**
1586   * Evaluates the fragment, returing the string value.
1587   */

1588  public String JavaDoc invokeTrim(JspFragment JavaDoc fragment)
1589    throws JspException JavaDoc, IOException JavaDoc
1590  {
1591    if (fragment == null)
1592      return "";
1593    
1594    BodyContentImpl body = (BodyContentImpl) pushBody();
1595
1596    try {
1597      fragment.invoke(body);
1598      return body.getTrimString();
1599    } finally {
1600      popBody();
1601      body.release();
1602    }
1603  }
1604
1605  /**
1606   * Evaluates the fragment, returing a reader
1607   */

1608  public Reader JavaDoc invokeReader(JspFragment JavaDoc fragment)
1609    throws JspException JavaDoc, IOException JavaDoc
1610  {
1611    if (fragment == null)
1612      return null;
1613    
1614    BodyContentImpl body = (BodyContentImpl) pushBody();
1615
1616    try {
1617      fragment.invoke(body);
1618
1619      return body.getReader();
1620    } finally {
1621      popBody();
1622      body.release();
1623    }
1624  }
1625
1626  /**
1627   * Parses a boolean value.
1628   */

1629  static public boolean toBoolean(String JavaDoc value)
1630  {
1631    if (value == null)
1632      return false;
1633    else if (value.equalsIgnoreCase("true"))
1634      return true;
1635    else if (value.equalsIgnoreCase("false"))
1636      return false;
1637    else
1638      return value.trim().equalsIgnoreCase("true");
1639  }
1640
1641  /**
1642   * Set/Remove a page attribute.
1643   */

1644  public void defaultSetOrRemove(String JavaDoc var, Object JavaDoc value)
1645  {
1646    if (value != null)
1647      putAttribute(var, value);
1648    else
1649      removeAttribute(var);
1650  }
1651
1652  /**
1653   * Set/Remove a page attribute.
1654   */

1655  public void pageSetOrRemove(String JavaDoc var, Object JavaDoc value)
1656  {
1657    if (value != null)
1658      _attributes.put(var, value);
1659    else
1660      _attributes.remove(var);
1661  }
1662
1663  /**
1664   * Set/Remove a request attribute.
1665   */

1666  public void requestSetOrRemove(String JavaDoc var, Object JavaDoc value)
1667  {
1668    if (value != null)
1669      getCauchoRequest().setAttribute(var, value);
1670    else
1671      getCauchoRequest().removeAttribute(var);
1672  }
1673  
1674  /**
1675   * Set/Remove a session attribute.
1676   */

1677  public void sessionSetOrRemove(String JavaDoc var, Object JavaDoc value)
1678  {
1679    if (value != null)
1680      getSession().setAttribute(var, value);
1681    else
1682      getSession().removeAttribute(var);
1683  }
1684
1685  /**
1686   * Set/Remove an webApp attribute.
1687   */

1688  public void applicationSetOrRemove(String JavaDoc var, Object JavaDoc value)
1689  {
1690    if (value != null)
1691      getApplication().setAttribute(var, value);
1692    else
1693      getApplication().removeAttribute(var);
1694  }
1695
1696  /**
1697   * Returns true if the EL ignores exceptions
1698   */

1699  public boolean isIgnoreException()
1700  {
1701    JspPropertyGroup jsp = getApplication().getJsp();
1702
1703    return (jsp == null || jsp.isIgnoreELException());
1704  }
1705
1706  /**
1707   * Returns the XPath variable environment corresponding to this page
1708   */

1709  public VarEnv getVarEnv()
1710  {
1711    if (_varEnv == null)
1712      _varEnv = new PageVarEnv();
1713
1714    return _varEnv;
1715  }
1716
1717  /**
1718   * Returns the XPath node environment corresponding to this page
1719   */

1720  public Node JavaDoc getNodeEnv()
1721  {
1722    return _nodeEnv;
1723  }
1724
1725  /**
1726   * Returns the XPath node environment corresponding to this page
1727   */

1728  public void setNodeEnv(Node JavaDoc node)
1729  {
1730    _nodeEnv = node;
1731  }
1732  
1733  /**
1734   * Finds an attribute in any of the scopes from page to webApp.
1735   *
1736   * @param name the attribute name.
1737   *
1738   * @return the attribute value
1739   */

1740  public Object JavaDoc resolveVariable(String JavaDoc name)
1741    throws javax.el.ELException
1742  {
1743    Object JavaDoc value = findAttribute(name);
1744
1745    if (value != null)
1746      return value;
1747
1748    if (_elContext == null)
1749      _elContext = EL.getEnvironment();
1750
1751    return _elContext.getELResolver().getValue(_elContext, name, null);
1752  }
1753
1754  /**
1755   * Returns the bundle manager.
1756   */

1757  private BundleManager getBundleManager()
1758  {
1759    if (_bundleManager == null)
1760      _bundleManager = BundleManager.create();
1761
1762    return _bundleManager;
1763  }
1764
1765  /**
1766   * Represents the XPath environment for this page.
1767   */

1768  public class PageVarEnv extends VarEnv {
1769    /**
1770     * Returns the value corresponding to the name.
1771     */

1772    public Object JavaDoc getValue(String JavaDoc name)
1773    {
1774      Object JavaDoc value = findAttribute(name);
1775
1776      if (value != null)
1777        return value;
1778
1779      int p = name.indexOf(':');
1780      if (p < 0)
1781        return null;
1782
1783      String JavaDoc prefix = name.substring(0, p);
1784      String JavaDoc suffix = name.substring(p + 1);
1785
1786      if (prefix.equals("param"))
1787        return getCauchoRequest().getParameter(suffix);
1788      else if (prefix.equals("header"))
1789        return ((HttpServletRequest JavaDoc) getCauchoRequest()).getHeader(suffix);
1790      else if (prefix.equals("cookie")) {
1791        Cookie JavaDoc cookie;
1792        HttpServletRequest JavaDoc request = (HttpServletRequest JavaDoc) getCauchoRequest();
1793
1794        if (request instanceof CauchoRequest)
1795          cookie = ((CauchoRequest) request).getCookie(suffix);
1796        else
1797          cookie = null;
1798
1799        if (cookie != null)
1800          return cookie.getValue();
1801        else
1802          return null;
1803      }
1804      else if (prefix.equals("initParam"))
1805        return getApplication().getInitParameter(suffix);
1806      else if (prefix.equals("pageScope"))
1807        return getAttribute(suffix);
1808      else if (prefix.equals("requestScope"))
1809        return getCauchoRequest().getAttribute(suffix);
1810      else if (prefix.equals("sessionScope"))
1811        return getSession().getAttribute(suffix);
1812      else if (prefix.equals("applicationScope"))
1813        return getApplication().getAttribute(suffix);
1814      else
1815        return null;
1816    }
1817  }
1818  
1819  static class StringArrayEnum implements Enumeration
1820  {
1821    private int _index;
1822    private String JavaDoc []_values;
1823
1824    StringArrayEnum(String JavaDoc []values)
1825    {
1826      _values = values;
1827    }
1828
1829    public boolean hasMoreElements()
1830    {
1831      return _index < _values.length;
1832    }
1833    
1834    public Object JavaDoc nextElement()
1835    {
1836      return _values[_index++];
1837    }
1838  }
1839
1840  public class PageELContext extends ELContext {
1841    public PageELContext()
1842    {
1843      putContext(JspContext JavaDoc.class, PageContextImpl.this);
1844    }
1845    
1846    public PageContextImpl getPageContext()
1847    {
1848      return PageContextImpl.this;
1849    }
1850    
1851    public ELResolver getELResolver()
1852    {
1853      return _elResolver;
1854    }
1855
1856    public javax.el.FunctionMapper getFunctionMapper()
1857    {
1858      return _functionMapper;
1859    }
1860
1861    public javax.el.VariableMapper getVariableMapper()
1862    {
1863      return _variableMapper;
1864    }
1865  }
1866
1867  public class PageFunctionMapper extends javax.el.FunctionMapper {
1868    public Method JavaDoc resolveFunction(String JavaDoc prefix, String JavaDoc localName)
1869    {
1870      if (_functionMap != null)
1871    return _functionMap.get(prefix + ":" + localName);
1872      else
1873    return null;
1874    }
1875  }
1876
1877  public class PageVariableMapper extends javax.el.VariableMapper {
1878    public ValueExpression resolveVariable(String JavaDoc var)
1879    {
1880      Object JavaDoc v = getAttribute(var);
1881
1882      if (v instanceof ValueExpression)
1883    return (ValueExpression) v;
1884      else
1885    return null;
1886    }
1887  
1888
1889    public ValueExpression setVariable(String JavaDoc variable,
1890                       ValueExpression expr)
1891    {
1892      return expr;
1893    }
1894  }
1895}
1896
Popular Tags