001: //** Copyright Statement ***************************************************
002: //The Salmon Open Framework for Internet Applications (SOFIA)
003: // Copyright (C) 1999 - 2002, Salmon LLC
004: //
005: // This program is free software; you can redistribute it and/or
006: // modify it under the terms of the GNU General Public License version 2
007: // as published by the Free Software Foundation;
008: //
009: // This program is distributed in the hope that it will be useful,
010: // but WITHOUT ANY WARRANTY; without even the implied warranty of
011: // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
012: // GNU General Public License for more details.
013: //
014: // You should have received a copy of the GNU General Public License
015: // along with this program; if not, write to the Free Software
016: // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
017: //
018: // For more information please visit http://www.salmonllc.com
019: //** End Copyright Statement ***************************************************
020: // ====================================================================
021: //
022: // The Apache Software License, Version 1.1
023: //
024: // Copyright (c) 1999 The Apache Software Foundation. All rights
025: // reserved.
026: //
027: // Redistribution and use in source and binary forms, with or without
028: // modification, are permitted provided that the following conditions
029: // are met:
030: //
031: // 1. Redistributions of source code must retain the above copyright
032: // notice, this list of conditions and the following disclaimer.
033: //
034: // 2. Redistributions in binary form must reproduce the above copyright
035: // notice, this list of conditions and the following disclaimer in
036: // the documentation and/or other materials provided with the
037: // distribution.
038: //
039: // 3. The end-user documentation included with the redistribution, if
040: // any, must include the following acknowlegement:
041: // "This product includes software developed by the
042: // Apache Software Foundation (http://www.apache.org/)."
043: // Alternately, this acknowlegement may appear in the software itself,
044: // if and wherever such third-party acknowlegements normally appear.
045: //
046: // 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
047: // Foundation" must not be used to endorse or promote products derived
048: // from this software without prior written permission. For written
049: // permission, please contact apache@apache.org.
050: //
051: // 5. Products derived from this software may not be called "Apache"
052: // nor may "Apache" appear in their names without prior written
053: // permission of the Apache Group.
054: //
055: // THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
056: // WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
057: // OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
058: // DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
059: // ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
060: // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
061: // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
062: // USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
063: // ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
064: // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
065: // OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
066: // SUCH DAMAGE.
067: // ====================================================================
068: //
069: // This software consists of voluntary contributions made by many
070: // individuals on behalf of the Apache Software Foundation. For more
071: // information on the Apache Software Foundation, please see
072: // <http://www.apache.org/>.
073:
074: package com.salmonllc.jsp.engine;
075:
076: /////////////////////////
077: //$Archive: /SOFIA/SourceCode/com/salmonllc/jsp/engine/PageContextImpl.java $
078: //$Author: Srufle $
079: //$Revision: 27 $
080: //$Modtime: 10/26/04 3:54p $
081: /////////////////////////
082: import com.salmonllc.util.MessageLog;
083:
084: import java.io.IOException;
085: import java.io.Serializable;
086:
087: import java.util.Enumeration;
088: import java.util.Hashtable;
089: import java.util.NoSuchElementException;
090: import java.util.Stack;
091:
092: import javax.servlet.Servlet;
093: import javax.servlet.ServletConfig;
094: import javax.servlet.ServletContext;
095: import javax.servlet.ServletRequest;
096: import javax.servlet.ServletResponse;
097: import javax.servlet.ServletException;
098:
099: import javax.servlet.http.HttpSession;
100: import javax.servlet.http.HttpServletRequest;
101:
102: import javax.servlet.jsp.PageContext;
103: import javax.servlet.jsp.JspWriter;
104: import javax.servlet.jsp.tagext.BodyContent;
105:
106: /**
107: * This class implements a J2EE Page Context Object.
108: */
109:
110: public class PageContextImpl extends PageContext implements
111: Serializable {
112: Stack _writerStack = new Stack();
113: protected Servlet _servlet;
114: protected ServletConfig _config;
115: protected ServletContext _context;
116: protected boolean _needsSession;
117: protected String _errorPageURL;
118: protected boolean _autoFlush;
119: protected int _bufferSize;
120:
121: protected transient Hashtable _attributes = new Hashtable(16);
122: protected transient ServletRequest _request;
123: protected transient ServletResponse _response;
124: protected transient Object _page;
125:
126: protected transient HttpSession _session;
127: protected transient JspWriter _out;
128:
129: private BodyContentImpl _dummyBodyContent;
130: private boolean _printContent = true;
131:
132: /**
133: * Empties the stack of JSPWriters used by this page context
134: */
135: public void clearWriterStack() throws IOException {
136: for (int i = 0; i < _writerStack.size(); i++) {
137: try {
138: JspWriter w = (JspWriter) _writerStack.elementAt(i);
139: if (w instanceof BodyContentImpl) {
140: ((BodyContentImpl) w).clearDreamWeaverConv();
141: w.clearBuffer();
142: BodyContentImpl
143: .freeBodyContent((BodyContentImpl) w);
144: }
145: } catch (Exception e) {
146: }
147: }
148: _writerStack.removeAllElements();
149:
150: }
151:
152: protected JspWriter createOut(int bufferSize, boolean autoFlush)
153: throws IOException, IllegalArgumentException {
154: try {
155: return new JspWriterImpl(_response, _bufferSize,
156: _autoFlush, _printContent);
157: } catch (Throwable t) {
158: MessageLog.writeErrorMessage("createOut", t, this );
159: return null;
160: }
161: }
162:
163: /**
164: * Searches for the named attribute in page, request, session (if valid), and application scope(s) in order and returns the value associated or null.
165: */
166: public Object findAttribute(String name) {
167: Object o = _attributes.get(name);
168: if (o != null)
169: return o;
170:
171: o = _request.getAttribute(name);
172: if (o != null)
173: return o;
174:
175: if (_session != null) {
176: o = _session.getAttribute(name);
177: if (o != null)
178: return o;
179: }
180:
181: return _context.getAttribute(name);
182: }
183:
184: /**
185: * This method is used to re-direct, or "forward" the current ServletRequest and ServletResponse to another active component in the application
186: */
187: public void forward(String relativeUrlPath)
188: throws ServletException, IOException {
189: String path = getAbsolutePathRelativeToContext(relativeUrlPath);
190: try {
191: _context.getRequestDispatcher(path).forward(_request,
192: _response);
193: } catch (ServletException e) {
194: MessageLog.writeErrorMessage("forward()", e, this );
195: throw e;
196: } catch (IOException e) {
197: MessageLog.writeErrorMessage("forward()", e, this );
198: throw e;
199: }
200: }
201:
202: private final String getAbsolutePathRelativeToContext(
203: String relativeUrlPath) {
204: String path = relativeUrlPath;
205:
206: if (!path.startsWith("/")) {
207: String uri = (String) _request
208: .getAttribute("javax.servlet.include.servlet_path");
209: if (uri == null)
210: uri = ((HttpServletRequest) _request).getServletPath();
211: String baseURI = uri.substring(0, uri.lastIndexOf('/'));
212: path = baseURI + '/' + path;
213: }
214:
215: return path;
216: }
217:
218: /**
219: * return the object associated with the name in the page scope or null
220: */
221:
222: public Object getAttribute(String name) {
223: return _attributes.get(name);
224: }
225:
226: /**
227: * return the object associated with the name in the page scope or null
228: */
229:
230: public Object getAttribute(String name, int scope) {
231: switch (scope) {
232: case PAGE_SCOPE:
233: return _attributes.get(name);
234:
235: case REQUEST_SCOPE:
236: return _request.getAttribute(name);
237:
238: case SESSION_SCOPE:
239: if (_session == null)
240: throw new IllegalArgumentException(
241: "can't access SESSION_SCOPE without an HttpSession");
242: else
243: return _session.getAttribute(name);
244:
245: case APPLICATION_SCOPE:
246: return _context.getAttribute(name);
247:
248: default:
249: throw new IllegalArgumentException("unidentified scope");
250: }
251: }
252:
253: /**
254: * Returns an enumeration of all the attributes in a specified scope
255: */
256: public Enumeration getAttributeNamesInScope(int scope) {
257: switch (scope) {
258: case PAGE_SCOPE:
259: return _attributes.keys();
260:
261: case REQUEST_SCOPE:
262: return _request.getAttributeNames();
263:
264: case SESSION_SCOPE:
265: if (_session != null) {
266: return _session.getAttributeNames();
267: } else
268: throw new IllegalArgumentException(
269: "can't access SESSION_SCOPE without an HttpSession");
270:
271: case APPLICATION_SCOPE:
272: return _context.getAttributeNames();
273:
274: default:
275: return new Enumeration() {
276: // empty enumeration
277: public boolean hasMoreElements() {
278: return false;
279: }
280:
281: public Object nextElement() {
282: throw new NoSuchElementException();
283: }
284: };
285: }
286: }
287:
288: /**
289: * Returns the scope of the object associated with the name specified or 0
290: */
291: public int getAttributesScope(String name) {
292: if (_attributes.get(name) != null)
293: return PAGE_SCOPE;
294:
295: if (_request.getAttribute(name) != null)
296: return REQUEST_SCOPE;
297:
298: if (_session != null) {
299: if (_session.getAttribute(name) != null)
300: return SESSION_SCOPE;
301: }
302:
303: if (_context.getAttribute(name) != null)
304: return APPLICATION_SCOPE;
305:
306: return 0;
307: }
308:
309: /**
310: * Returns any exception passed to this as an errorpage
311: */
312: public Exception getException() {
313: return (Exception) _request.getAttribute(EXCEPTION);
314: }
315:
316: /**
317: * Returns the current JspWriter stream being used for client response
318: */
319: public JspWriter getOut() {
320: return _out;
321: }
322:
323: /**
324: * Returns the Page implementation class instance (Servlet) associated with this PageContext
325: */
326: public Object getPage() {
327: return _servlet;
328: }
329:
330: /**
331: * Returns the ServletRequest for this PageContext
332: */
333: public ServletRequest getRequest() {
334: return _request;
335: }
336:
337: /**
338: * Returns the ServletResponse for this PageContext
339: */
340: public ServletResponse getResponse() {
341: return _response;
342: }
343:
344: /**
345: * Returns the Servlet for this PageContext
346: */
347: public Servlet getServlet() {
348: return _servlet;
349: }
350:
351: /**
352: * Returns the ServletConfig for this PageContext
353: */
354:
355: public ServletConfig getServletConfig() {
356: return _config;
357: }
358:
359: /**
360: * Returns the ServletContext for this PageContext
361: */
362:
363: public ServletContext getServletContext() {
364: return _config.getServletContext();
365: }
366:
367: /**
368: * Returns the current user session
369: */
370: public HttpSession getSession() {
371: return _session;
372: }
373:
374: /**
375: * returns the stack of writers used by the page.
376: */
377: public Stack getStack() {
378: return _writerStack;
379: }
380:
381: /**
382: * This method is intended to process an unhandled "page" level exception by redirecting the exception to either the specified error page for this JSP, or if none was specified, to perform some implementation dependent action.
383: */
384: public void handlePageException(Exception e) throws IOException,
385: ServletException {
386:
387: // set the request attribute with the exception.
388: _request.setAttribute("javax.servlet.jsp.jspException", e);
389:
390: if (_errorPageURL != null && !_errorPageURL.equals("")) {
391: try {
392: forward(_errorPageURL);
393: } catch (IllegalStateException ise) {
394: include(_errorPageURL);
395: }
396: } // Otherwise throw the exception wrapped inside a ServletException.
397: else {
398: // Set the exception as the root cause in the ServletException
399: // to get a stack trace for the real problem
400: if (e instanceof IOException)
401: throw (IOException) e;
402: if (e instanceof ServletException)
403: throw (ServletException) e;
404: // e.printStackTrace();
405: throw new ServletException(e);
406: }
407:
408: }
409:
410: /**
411: * This method is intended to process an unhandled "page" level exception by redirecting the exception to either the specified error page for this JSP, or if none was specified, to perform some implementation dependent action
412: */
413: public void handlePageException(Throwable throwable)
414: throws ServletException, IOException {
415: MessageLog.writeErrorMessage(throwable, this );
416: }
417:
418: /**
419: * Causes the resource specified to be processed as part of the current ServletRequest and ServletResponse being processed by the calling Thread.
420: */
421: public void include(String relativeUrlPath)
422: throws ServletException, IOException {
423: String path = getAbsolutePathRelativeToContext(relativeUrlPath);
424: javax.servlet.RequestDispatcher d = _context
425: .getRequestDispatcher(path);
426:
427: //weblogic 6 & Silverstream gets upset if you pass anything but the original response to the include method
428: //Tomcat calls the flushbuffer, which causes things like send redirect to fail.
429: //This provides a work around for everybody (tomcat always gets a dummy response that it can do anything to and can't break anything)
430: //Weblogic & Silverstream gets the real response which it doesn't seem to break
431:
432: //Uncomment the line below for Debugging Purposes if you have a problem with a particular Web Server
433: //System.out.println("d Class Name is "+d.getClass().getName());
434: try {
435: if (_printContent
436: || d.getClass().getName().startsWith("weblogic")
437: || d.getClass().getName().startsWith("com.sssw")) {
438: _out.flush();
439: d.include(_request, _response);
440: } else {
441: d
442: .include(
443: _request,
444: new com.salmonllc.html.HttpServletResponseDummy(
445: null, null));
446: }
447: } catch (ServletException e) {
448: MessageLog.writeErrorMessage("include()", e, this );
449: throw e;
450: } catch (IOException e) {
451: MessageLog.writeErrorMessage("include()", e, this );
452: throw e;
453: }
454: }
455:
456: /**
457: * The initialize emthod is called to initialize an uninitialized PageContext so that it may be used by a JSP Implementation class to service an incoming request and response wihtin it's _jspService() method.<BR><BR>
458: * This method is typically called from JspFactory.getPageContext() in order to initialize state.<BR><BR>
459: * This method is required to create an initial JspWriter, and associate the "out" name in page scope with this newly created object.
460: */
461: public void initialize(Servlet servlet, ServletRequest request,
462: ServletResponse response, String errorPageURL,
463: boolean needsSession, int bufferSize, boolean autoFlush)
464: throws IOException, IllegalStateException,
465: IllegalArgumentException {
466:
467: // initialize state
468:
469: _servlet = servlet;
470: _config = _servlet.getServletConfig();
471: _context = _config.getServletContext();
472: _needsSession = needsSession;
473: _errorPageURL = errorPageURL;
474: _bufferSize = bufferSize;
475: _autoFlush = autoFlush;
476: _request = request;
477: _response = response;
478:
479: // setup session (if required)
480: if (_request instanceof HttpServletRequest && needsSession)
481: _session = ((HttpServletRequest) _request).getSession();
482:
483: if (needsSession && _session == null)
484: throw new IllegalStateException(
485: "Page needs a session and none is available");
486:
487: // initialize the initial out ...
488: // System.out.println("Initialize PageContextImpl " + out );
489: if (_out == null) {
490: _out = createOut(bufferSize, autoFlush); // throws
491: } else
492: ((JspWriterImpl) _out)
493: .init(response, bufferSize, autoFlush);
494:
495: if (_out == null)
496: throw new IllegalStateException(
497: "failed initialize JspWriter");
498:
499: // register names/values as per spec
500:
501: setAttribute(OUT, _out);
502: setAttribute(REQUEST, request);
503: setAttribute(RESPONSE, response);
504:
505: if (_session != null)
506: setAttribute(SESSION, _session);
507:
508: setAttribute(PAGE, servlet);
509: setAttribute(CONFIG, _config);
510: setAttribute(PAGECONTEXT, this );
511: setAttribute(APPLICATION, _context);
512: }
513:
514: /**
515: * Return the previous JspWriter "out" saved by the matching pushBody(), and update the value of the "out" attribute in the page scope attribute namespace of the PageConxtext
516: */
517: public JspWriter popBody() {
518: if (_out instanceof BodyContentImpl
519: && (!(_out == _dummyBodyContent))) {
520: BodyContentImpl.freeBodyContent((BodyContentImpl) _out);
521: ((BodyContentImpl) _out).clearDreamWeaverConv();
522: }
523: _out = (JspWriter) _writerStack.pop();
524: return _out;
525: }
526:
527: /**
528: * Return a new BodyContent object, save the current "out" JspWriter, and update the value of the "out" attribute in the page scope attribute namespace of the PageContext
529: */
530: public BodyContent pushBody() {
531: if (_printContent) {
532: JspWriter previous = _out;
533: _writerStack.push(_out);
534: _out = BodyContentImpl.getBodyContent(previous,
535: _printContent);
536: } else {
537: _writerStack.push(_out);
538: if (_dummyBodyContent == null)
539: _dummyBodyContent = new BodyContentImpl(_out,
540: _printContent);
541: _dummyBodyContent.setPrintContent(false);
542: _out = _dummyBodyContent;
543: }
544: return (BodyContent) _out;
545: }
546:
547: /**
548: * This method shall "reset" the internal state of a PageContext, releasing all internal references, and preparing the PageContext for potential reuse by a later invocation of initialize().
549: */
550: public void release() {
551: _servlet = null;
552: _config = null;
553: _context = null;
554: _needsSession = false;
555: _errorPageURL = null;
556: _bufferSize = JspWriter.DEFAULT_BUFFER;
557: _autoFlush = true;
558: _request = null;
559: _response = null;
560: if (_out instanceof JspWriterImpl)
561: ((JspWriterImpl) _out).recycle();
562: _session = null;
563: _out = null;
564: try {
565: clearWriterStack();
566: } catch (Exception e) {
567: }
568: _attributes.clear();
569:
570: _writerStack = null;
571: _attributes = null;
572: _page = null;
573: _dummyBodyContent = null;
574:
575: }
576:
577: /**
578: * remove the object reference associated with the specified name
579: */
580: public void removeAttribute(String name) {
581: try {
582: removeAttribute(name, PAGE_SCOPE);
583: removeAttribute(name, REQUEST_SCOPE);
584: removeAttribute(name, SESSION_SCOPE);
585: removeAttribute(name, APPLICATION_SCOPE);
586: } catch (Exception ex) {
587: // we remove as much as we can, and
588: // simply ignore possible exceptions
589: }
590: }
591:
592: /**
593: * remove the object reference associated with the specified name
594: */
595: public void removeAttribute(String name, int scope) {
596: switch (scope) {
597: case PAGE_SCOPE:
598: _attributes.remove(name);
599: break;
600:
601: case REQUEST_SCOPE:
602: _request.removeAttribute(name);
603:
604: case SESSION_SCOPE:
605: if (_session == null)
606: throw new IllegalArgumentException(
607: "can't access SESSION_SCOPE without an HttpSession");
608: else
609: _session.removeAttribute(name);
610: break;
611:
612: case APPLICATION_SCOPE:
613: _context.removeAttribute(name);
614: break;
615:
616: default:
617: }
618: }
619:
620: /**
621: * Changes the servlet response for the context
622: */
623: public void replaceResponse(ServletResponse res) {
624: _response = res;
625:
626: }
627:
628: /**
629: * register the name and object specified with appropriate scope semantics
630: */
631: public void setAttribute(String name, Object attribute) {
632: _attributes.put(name, attribute);
633: }
634:
635: /**
636: * register the name and object specified with appropriate scope semantics
637: */
638: public void setAttribute(String name, Object o, int scope) {
639: switch (scope) {
640: case PAGE_SCOPE:
641: _attributes.put(name, o);
642: break;
643:
644: case REQUEST_SCOPE:
645: _request.setAttribute(name, o);
646: break;
647:
648: case SESSION_SCOPE:
649: if (_session == null)
650: throw new IllegalArgumentException(
651: "can't access SESSION_SCOPE without an HttpSession");
652: else
653: _session.setAttribute(name, o);
654: break;
655:
656: case APPLICATION_SCOPE:
657: _context.setAttribute(name, o);
658: break;
659:
660: default:
661: }
662: }
663:
664: /**
665: * Set whether the Impl will return a real BodyContent or a stub
666: */
667: public void setPrintContent(boolean print) {
668: _printContent = print;
669: }
670: }
|