001    package railo.runtime;
002    
003    
004    import java.io.IOException;
005    import java.io.OutputStream;
006    import java.util.Date;
007    import java.util.Enumeration;
008    import java.util.HashMap;
009    import java.util.HashSet;
010    import java.util.LinkedList;
011    import java.util.List;
012    import java.util.Locale;
013    import java.util.Map;
014    import java.util.Map.Entry;
015    import java.util.Set;
016    import java.util.TimeZone;
017    
018    import javax.servlet.Servlet;
019    import javax.servlet.ServletConfig;
020    import javax.servlet.ServletContext;
021    import javax.servlet.ServletException;
022    import javax.servlet.ServletOutputStream;
023    import javax.servlet.ServletRequest;
024    import javax.servlet.ServletResponse;
025    import javax.servlet.http.HttpServlet;
026    import javax.servlet.http.HttpServletRequest;
027    import javax.servlet.http.HttpServletResponse;
028    import javax.servlet.http.HttpSession;
029    import javax.servlet.jsp.JspException;
030    import javax.servlet.jsp.JspWriter;
031    import javax.servlet.jsp.tagext.BodyContent;
032    import javax.servlet.jsp.tagext.BodyTag;
033    import javax.servlet.jsp.tagext.Tag;
034    import javax.servlet.jsp.tagext.TryCatchFinally;
035    
036    import org.apache.oro.text.regex.MalformedPatternException;
037    import org.apache.oro.text.regex.Pattern;
038    import org.apache.oro.text.regex.PatternMatcherInput;
039    import org.apache.oro.text.regex.Perl5Compiler;
040    import org.apache.oro.text.regex.Perl5Matcher;
041    
042    import railo.commons.io.BodyContentStack;
043    import railo.commons.io.IOUtil;
044    import railo.commons.io.res.Resource;
045    import railo.commons.io.res.util.ResourceUtil;
046    import railo.commons.lang.SizeOf;
047    import railo.commons.lang.StringUtil;
048    import railo.commons.lang.SystemOut;
049    import railo.commons.lang.types.RefBoolean;
050    import railo.commons.lang.types.RefBooleanImpl;
051    import railo.commons.lock.KeyLock;
052    import railo.commons.lock.Lock;
053    import railo.commons.net.HTTPUtil;
054    import railo.intergral.fusiondebug.server.FDSignal;
055    import railo.runtime.component.ComponentLoader;
056    import railo.runtime.config.Config;
057    import railo.runtime.config.ConfigImpl;
058    import railo.runtime.config.ConfigServerImpl;
059    import railo.runtime.config.ConfigWeb;
060    import railo.runtime.config.ConfigWebImpl;
061    import railo.runtime.db.DataSource;
062    import railo.runtime.db.DataSourceManager;
063    import railo.runtime.db.DatasourceConnection;
064    import railo.runtime.db.DatasourceConnectionPool;
065    import railo.runtime.db.DatasourceManagerImpl;
066    import railo.runtime.debug.DebugEntry;
067    import railo.runtime.debug.Debugger;
068    import railo.runtime.debug.DebuggerImpl;
069    import railo.runtime.dump.DumpUtil;
070    import railo.runtime.engine.ExecutionLog;
071    import railo.runtime.err.ErrorPage;
072    import railo.runtime.err.ErrorPageImpl;
073    import railo.runtime.err.ErrorPagePool;
074    import railo.runtime.exp.Abort;
075    import railo.runtime.exp.ApplicationException;
076    import railo.runtime.exp.CasterException;
077    import railo.runtime.exp.ExceptionHandler;
078    import railo.runtime.exp.ExpressionException;
079    import railo.runtime.exp.MissingIncludeException;
080    import railo.runtime.exp.PageException;
081    import railo.runtime.exp.PageExceptionBox;
082    import railo.runtime.exp.PageServletException;
083    import railo.runtime.interpreter.CFMLExpressionInterpreter;
084    import railo.runtime.interpreter.VariableInterpreter;
085    import railo.runtime.listener.AppListenerSupport;
086    import railo.runtime.listener.ApplicationContextPro;
087    import railo.runtime.listener.ApplicationListener;
088    import railo.runtime.listener.ClassicApplicationContext;
089    import railo.runtime.listener.ModernAppListenerException;
090    import railo.runtime.monitor.RequestMonitor;
091    import railo.runtime.net.ftp.FTPPool;
092    import railo.runtime.net.ftp.FTPPoolImpl;
093    import railo.runtime.net.http.HTTPServletRequestWrap;
094    import railo.runtime.op.Caster;
095    import railo.runtime.op.Decision;
096    import railo.runtime.orm.ORMConfiguration;
097    import railo.runtime.orm.ORMEngine;
098    import railo.runtime.orm.ORMSession;
099    import railo.runtime.query.QueryCache;
100    import railo.runtime.security.Credential;
101    import railo.runtime.security.CredentialImpl;
102    import railo.runtime.tag.Login;
103    import railo.runtime.tag.TagHandlerPool;
104    import railo.runtime.tag.util.DeprecatedUtil;
105    import railo.runtime.type.Array;
106    import railo.runtime.type.Collection;
107    import railo.runtime.type.Collection.Key;
108    import railo.runtime.type.Iterator;
109    import railo.runtime.type.KeyImpl;
110    import railo.runtime.type.Query;
111    import railo.runtime.type.SVArray;
112    import railo.runtime.type.Scope;
113    import railo.runtime.type.Sizeable;
114    import railo.runtime.type.Struct;
115    import railo.runtime.type.StructImpl;
116    import railo.runtime.type.UDF;
117    import railo.runtime.type.it.KeyIterator;
118    import railo.runtime.type.ref.Reference;
119    import railo.runtime.type.ref.VariableReference;
120    import railo.runtime.type.scope.Application;
121    import railo.runtime.type.scope.Argument;
122    import railo.runtime.type.scope.ArgumentImpl;
123    import railo.runtime.type.scope.CGI;
124    import railo.runtime.type.scope.CGIImpl;
125    import railo.runtime.type.scope.Client;
126    import railo.runtime.type.scope.ClientPlus;
127    import railo.runtime.type.scope.Cluster;
128    import railo.runtime.type.scope.Cookie;
129    import railo.runtime.type.scope.CookieImpl;
130    import railo.runtime.type.scope.Form;
131    import railo.runtime.type.scope.FormImpl;
132    import railo.runtime.type.scope.LocalNotSupportedScope;
133    import railo.runtime.type.scope.LocalPro;
134    import railo.runtime.type.scope.Request;
135    import railo.runtime.type.scope.RequestImpl;
136    import railo.runtime.type.scope.ScopeContext;
137    import railo.runtime.type.scope.ScopeFactory;
138    import railo.runtime.type.scope.ScopeSupport;
139    import railo.runtime.type.scope.Server;
140    import railo.runtime.type.scope.Session;
141    import railo.runtime.type.scope.SessionPlus;
142    import railo.runtime.type.scope.Threads;
143    import railo.runtime.type.scope.URL;
144    import railo.runtime.type.scope.URLForm;
145    import railo.runtime.type.scope.URLImpl;
146    import railo.runtime.type.scope.Undefined;
147    import railo.runtime.type.scope.UndefinedImpl;
148    import railo.runtime.type.scope.UrlFormImpl;
149    import railo.runtime.type.scope.Variables;
150    import railo.runtime.type.scope.VariablesImpl;
151    import railo.runtime.util.ApplicationContext;
152    import railo.runtime.util.VariableUtil;
153    import railo.runtime.util.VariableUtilImpl;
154    import railo.runtime.writer.CFMLWriter;
155    import railo.runtime.writer.DevNullBodyContent;
156    
157    /**
158     * page context for every page object. 
159     * the PageContext is a jsp page context expanded by cold fusion functionality.
160     * for example you have the method getSession to get jsp combatible session object (HTTPSession)
161     *  and with sessionScope() you get CFML combatible session object (Struct,Scope).
162     */
163    public final class PageContextImpl extends PageContext implements Sizeable {
164            
165            private static final RefBoolean DUMMY_BOOL = new RefBooleanImpl(false);
166            private static final Key CFCATCH = KeyImpl.intern("cfcatch");
167            private static final Key CATCH = KeyImpl.intern("catch");
168            private static final Key CFTHREAD = KeyImpl.intern("cfthread");
169            private static final Key ERROR = KeyImpl.intern("error");
170            private static final Key CFERROR = KeyImpl.intern("cferror");
171            
172            private static int counter=0;
173            
174            /** 
175             * Field <code>pathList</code>
176             */
177        private LinkedList<PageSource> pathList=new LinkedList<PageSource>();
178        private LinkedList<PageSource> includePathList=new LinkedList<PageSource>();
179            
180            /**
181             * Field <code>executionTime</code>
182             */
183            protected int executionTime=0;
184            
185            private HTTPServletRequestWrap req;
186            private HttpServletResponse rsp;
187            private HttpServlet servlet;
188            
189            private JspWriter writer;
190        private JspWriter forceWriter;
191        private BodyContentStack bodyContentStack;
192        private DevNullBodyContent devNull;
193        
194            private ConfigWebImpl config;
195            //private DataSourceManager manager;
196            //private CFMLCompilerImpl compiler;
197            
198            // Scopes
199            private ScopeContext scopeContext;
200        private Variables variablesRoot=new VariablesImpl();//ScopeSupport(false,"variables",Scope.SCOPE_VARIABLES);
201        private Variables variables=variablesRoot;//new ScopeSupport("variables",Scope.SCOPE_VARIABLES);
202        private UndefinedImpl undefined;
203            
204        private URLImpl _url=new URLImpl();
205            private FormImpl _form=new FormImpl();
206            
207            private URLForm urlForm=new UrlFormImpl(_form,_url);
208            private URL url;
209            private Form form;
210            
211            
212            private RequestImpl request=new RequestImpl();
213            private CGIImpl cgi=new CGIImpl();      
214            private Argument argument=new ArgumentImpl();
215        private static LocalNotSupportedScope localUnsupportedScope=LocalNotSupportedScope.getInstance();
216            private LocalPro local=localUnsupportedScope;
217            private SessionPlus session;
218            private Server server;
219            private Cluster cluster;
220            private CookieImpl cookie=new CookieImpl();
221            private ClientPlus client;
222            private Application application;
223    
224        private DebuggerImpl debugger=new DebuggerImpl();
225            private long requestTimeout=-1;
226            private short enablecfoutputonly=0;
227            private int outputState;
228            private String cfid;
229            private String cftoken;
230    
231            private int id;
232            private int requestId;
233            
234            
235            private boolean psq;
236            private Locale locale;
237            private TimeZone timeZone;
238            
239        // Pools
240        private ErrorPagePool errorPagePool=new ErrorPagePool();
241            private TagHandlerPool tagHandlerPool;
242            private FTPPool ftpPool=new FTPPoolImpl();
243            private QueryCache queryCache;
244    
245            private Component activeComponent;
246            private UDF activeUDF;
247        //private ComponentScope componentScope=new ComponentScope(this);
248            
249            private Credential remoteUser;
250        
251        protected VariableUtilImpl variableUtil=new VariableUtilImpl();
252    
253        private PageException exception;
254        private PageSource base;
255    
256        ApplicationContextPro applicationContext;
257        ApplicationContextPro defaultApplicationContext;
258    
259        private ScopeFactory scopeFactory=new ScopeFactory();
260    
261        private Tag parentTag=null;
262        private Tag currentTag=null;
263        private Thread thread;
264        private long startTime;
265            private boolean isCFCRequest;
266            
267            private DatasourceManagerImpl manager;
268            private Struct threads;
269            private boolean hasFamily=false;
270            //private CFMLFactoryImpl factory;
271            private PageContextImpl parent;
272            private Map<String,DatasourceConnection> conns=new HashMap<String,DatasourceConnection>();
273            private boolean fdEnabled;
274            private ExecutionLog execLog;
275            private boolean useSpecialMappings;
276            
277    
278            private ORMSession ormSession;
279            private boolean isChild;
280            private boolean gatewayContext;
281            private String serverPassword;
282    
283            public long sizeOf() {
284                    
285                    return 
286                    SizeOf.size(pathList)+
287                    SizeOf.size(includePathList)+
288                    SizeOf.size(executionTime)+
289                    SizeOf.size(writer)+
290                    SizeOf.size(forceWriter)+
291                    SizeOf.size(bodyContentStack)+
292                    SizeOf.size(variables)+
293                    SizeOf.size(url)+
294                    SizeOf.size(form)+
295                    SizeOf.size(_url)+
296                    SizeOf.size(_form)+
297                    SizeOf.size(request)+
298    
299                    SizeOf.size(argument)+
300                    SizeOf.size(local)+
301                    SizeOf.size(cookie)+
302                    SizeOf.size(debugger)+
303                    SizeOf.size(requestTimeout)+
304                    SizeOf.size(enablecfoutputonly)+
305                    SizeOf.size(outputState)+
306                    SizeOf.size(cfid)+
307                    SizeOf.size(cftoken)+
308                    SizeOf.size(id)+
309                    SizeOf.size(psq)+
310                    SizeOf.size(locale)+
311                    SizeOf.size(errorPagePool)+
312                    SizeOf.size(tagHandlerPool)+
313                    SizeOf.size(ftpPool)+
314                    SizeOf.size(activeComponent)+
315                    SizeOf.size(activeUDF)+
316                    SizeOf.size(remoteUser)+
317                    SizeOf.size(exception)+
318                    SizeOf.size(base)+
319                    SizeOf.size(applicationContext)+
320                    SizeOf.size(defaultApplicationContext)+
321                    SizeOf.size(parentTag)+
322                    SizeOf.size(currentTag)+
323                    SizeOf.size(startTime)+
324                    SizeOf.size(isCFCRequest)+
325                    SizeOf.size(conns)+
326                    SizeOf.size(serverPassword)+
327                    SizeOf.size(ormSession);
328            }
329            
330            
331    
332            /** 
333             * default Constructor
334             * @param factoryImpl 
335             * @param scopeContext
336             * @param config Configuration of the Cold Fusion Container
337             * @param compiler CFML Compiler
338             * @param queryCache Query Cache Object
339             * @param id identity of the pageContext
340             */
341            public PageContextImpl(ScopeContext scopeContext, ConfigWebImpl config, QueryCache queryCache,int id,HttpServlet servlet) {
342                    // must be first because is used after
343                    tagHandlerPool=config.getTagHandlerPool();
344            this.servlet=servlet;
345                    this.id=id;
346                    //this.factory=factory;
347                    
348            bodyContentStack=new BodyContentStack();
349            devNull=bodyContentStack.getDevNullBodyContent();
350            
351            this.config=config;
352            manager=new DatasourceManagerImpl(config);
353            
354                this.scopeContext=scopeContext;
355            undefined=
356                    new UndefinedImpl(this,config.getScopeCascadingType());
357            
358            
359                    //this.compiler=compiler;
360            //tagHandlerPool=config.getTagHandlerPool();
361                    this.queryCache=queryCache;
362                    server=ScopeContext.getServerScope(this);
363                    
364                    defaultApplicationContext=new ClassicApplicationContext(config,"",true,null);
365                    
366            }
367            
368            /**
369             * initialize a existing page context
370             * @param servlet
371             * @param req
372             * @param rsp
373             * @param errorPageURL
374             * @param needsSession
375             * @param bufferSize
376             * @param autoFlush
377             */
378            public PageContextImpl initialize(
379                             HttpServlet servlet, 
380                             HttpServletRequest req, 
381                             HttpServletResponse rsp, 
382                             String errorPageURL, 
383                             boolean needsSession, 
384                             int bufferSize, 
385                             boolean autoFlush,boolean isChild) {
386                    requestId=counter++;
387                    rsp.setContentType("text/html; charset=UTF-8");
388                    
389                    this.isChild=isChild;
390                    
391            //rsp.setHeader("Connection", "close");
392            applicationContext=defaultApplicationContext;
393            
394            startTime=System.currentTimeMillis();
395            thread=Thread.currentThread();
396            
397            isCFCRequest = StringUtil.endsWithIgnoreCase(req.getServletPath(),".cfc");
398            
399            this.req=new HTTPServletRequestWrap(req);
400            this.rsp=rsp;
401            this.servlet=servlet;
402    
403             // Writers
404             bodyContentStack.init(req,rsp,config.isSuppressWhitespace(),config.closeConnection(),config.isShowVersion(),config.contentLength(),config.allowCompression());
405                     writer=bodyContentStack.getWriter();
406             forceWriter=writer;
407             
408                     // Scopes
409             server=ScopeContext.getServerScope(this);
410             if(hasFamily) {
411                     variablesRoot=new VariablesImpl();
412                     variables=variablesRoot;
413                     request=new RequestImpl();
414                     _url=new URLImpl();
415                     _form=new FormImpl();
416                     urlForm=new UrlFormImpl(_form,_url);
417                     undefined=
418                    new UndefinedImpl(this,config.getScopeCascadingType());
419                     
420                     hasFamily=false;
421             }
422             request.initialize(this);
423             
424                     if(config.mergeFormAndURL()) {
425                             url=urlForm;
426                             form=urlForm;
427                     }
428                     else {
429                             url=_url;
430                             form=_form;
431                     }
432             //url.initialize(this);
433                     //form.initialize(this);
434                     //undefined.initialize(this);
435                     
436             
437            psq=config.getPSQL();
438                    
439                    fdEnabled=!config.allowRequestTimeout();
440                    
441                    if(config.getExecutionLogEnabled())
442                            this.execLog=config.getExecutionLogFactory().getInstance(this);
443                    
444            return this;
445             }
446            
447            /**
448             * @see javax.servlet.jsp.PageContext#release()
449             */
450            public void release() {//KeyImpl.dump();
451                    this.serverPassword=null;
452                    boolean isChild=parent!=null;
453                    parent=null;
454                    // Attention have to be before close
455                    if(client!=null){
456                    client.touchAfterRequest(this);
457                    client=null;
458            }
459                    if(session!=null){
460                    session.touchAfterRequest(this);
461                    session=null;
462            }
463                    
464                    // ORM
465            if(ormSession!=null){
466                    // flush orm session
467                    try {
468                                    ORMEngine engine=ormSession.getEngine();
469                            ORMConfiguration config=engine.getConfiguration(this);
470                            if(config==null || (config.flushAtRequestEnd() && config.autoManageSession())){
471                                            ormSession.flush(this);
472                                            //ormSession.close(this);
473                                            //print.err("2orm flush:"+Thread.currentThread().getId());
474                                    }
475                                    ormSession.close(this);
476                            } 
477                    catch (Throwable t) {
478                            //print.printST(t);
479                    }
480                    
481                            
482                    // release connection
483                            DatasourceConnectionPool pool = this.config.getDatasourceConnectionPool();
484                            DatasourceConnection dc=ormSession.getDatasourceConnection();
485                            if(dc!=null)pool.releaseDatasourceConnection(dc);
486                   
487                    ormSession=null;
488            }
489            
490                    
491                    close();
492            thread=null;
493            base=null;
494            //RequestImpl r = request;
495            
496            // Scopes
497            if(hasFamily) {
498                    if(!isChild){
499                            req.disconnect();
500                    }
501                    
502                    request=null;
503                    _url=null;
504                    _form=null;
505                urlForm=null;
506                undefined=null;
507                variables=null;
508                variablesRoot=null;
509                if(threads!=null && threads.size()>0) threads.clear();
510                
511            }
512            else {
513                variables=variablesRoot;
514                variables.release();
515                undefined.release();
516                urlForm.release();
517                    request.release();
518            }
519            cgi.release();
520            argument.release();
521            local=localUnsupportedScope;
522            
523            cookie.release();
524                    //if(cluster!=null)cluster.release();
525            
526            //client=null;
527            //session=null;
528            
529                    
530            
531            
532                    application=null;// not needed at the moment -> application.releaseAfterRequest();
533                    applicationContext=null;
534                    
535                    // Properties
536            requestTimeout=-1;
537            outputState=0;
538            cfid=null;
539            cftoken=null;
540            locale=null;
541            timeZone=null;
542            url=null;
543            form=null;
544            if(config.debug()) debugger.reset();
545            
546            // Pools
547            errorPagePool.clear();
548    
549            // transaction connection
550            if(!conns.isEmpty()){
551                    java.util.Iterator<Entry<String, DatasourceConnection>> it = conns.entrySet().iterator();
552                    DatasourceConnectionPool pool = config.getDatasourceConnectionPool();
553                    while(it.hasNext())     {
554                            pool.releaseDatasourceConnection((it.next().getValue()));
555                    }
556                    conns.clear();
557            }
558            
559            
560            
561            pathList.clear();
562            includePathList.clear();
563                    executionTime=0;
564                    
565                    bodyContentStack.release();
566                    
567    
568            
569                    //activeComponent=null;
570                    remoteUser=null;
571                    exception=null;
572                    ftpPool.clear();
573            parentTag=null;
574            currentTag=null;
575            
576            // Req/Rsp
577            //if(req!=null)
578                    req.clear();
579            req=null;
580            rsp=null;
581            servlet=null;
582    
583            // Writer
584            writer=null;
585            forceWriter=null;
586            if(pagesUsed.size()>0)pagesUsed.clear();
587            
588            activeComponent=null;
589            activeUDF=null;
590            
591            if(config.getExecutionLogEnabled()){
592                    execLog.release();
593                            execLog=null;
594            }
595    
596            gatewayContext=false;
597            
598            manager.release();
599            }
600    
601            /**
602             * @see javax.servlet.jsp.PageContext#initialize(javax.servlet.Servlet, javax.servlet.ServletRequest, javax.servlet.ServletResponse, java.lang.String, boolean, int, boolean)
603             */
604            public void initialize(
605                            Servlet servlet, 
606                            ServletRequest req, 
607                            ServletResponse rsp, 
608                            String errorPageURL, 
609                            boolean needsSession, 
610                            int bufferSize, 
611                            boolean autoFlush) throws IOException, IllegalStateException, IllegalArgumentException {
612               initialize((HttpServlet)servlet,(HttpServletRequest)req,(HttpServletResponse)rsp,errorPageURL,needsSession,bufferSize,autoFlush);
613            }
614            
615            // FUTURE add to abstract class
616            
617            /* *
618             * called when parent thread end
619             * /
620            public void unlink() {
621                    
622                    //print.o(request.keysAsString());
623                    // unlink request scope
624                    HttpServletRequest org = req.getOriginalRequest();
625                    if(org instanceof HttpServletRequestDummy) {
626                            ((HttpServletRequestDummy)org).setAttributes(new StructImpl());
627                    }
628                    
629                    RequestImpl r = new RequestImpl();
630                    r.initialize(this);
631                    StructImpl.copy(request,r,false);
632                    //print.o(request.keysAsString());
633                    //print.o(r.keysAsString());
634                    this.request=r;
635            }*/
636    
637        /**
638         * @see railo.runtime.PageContext#write(java.lang.String)
639         */
640        public void write(String str) throws IOException {
641            writer.write(str);
642            }
643    
644        /**
645         * @see railo.runtime.PageContext#forceWrite(java.lang.String)
646         */
647        public void forceWrite(String str) throws IOException {
648            forceWriter.write(str);
649        }
650            
651        /**
652         * @see railo.runtime.PageContext#writePSQ(java.lang.Object)
653         */
654        public void writePSQ(Object o) throws IOException, PageException {
655            if(o instanceof Date || Decision.isDate(o, false)) {
656                            writer.write(Caster.toString(o));
657                    }
658                    else {
659                writer.write(psq?Caster.toString(o):StringUtil.replace(Caster.toString(o),"'","''",false));
660                    }
661            } 
662            
663        /**
664         * @see railo.runtime.PageContext#flush()
665         */
666        public void flush() {
667                    try {
668                            getOut().flush();
669                    } catch (IOException e) {}
670            }
671            
672        /**
673         * @see railo.runtime.PageContext#close()
674         */
675        public void close() {
676                    IOUtil.closeEL(getOut());
677            }
678            
679        /**
680         * @see railo.runtime.PageContext#getRelativePageSource(java.lang.String)
681         */
682        public PageSource getRelativePageSource(String realPath) {
683            SystemOut.print(config.getOutWriter(),"method getRelativePageSource is deprecated");
684            if(StringUtil.startsWith(realPath,'/')) return PageSourceImpl.best(getPageSources(realPath));
685            if(pathList.size()==0) return null;
686                    return ((PageSource) pathList.getLast()).getRealPage(realPath);
687            }
688        
689        public PageSource getRelativePageSourceExisting(String realPath) {
690            if(StringUtil.startsWith(realPath,'/')) return getPageSourceExisting(realPath);
691            if(pathList.size()==0) return null;
692                    PageSource ps = pathList.getLast().getRealPage(realPath);
693                    if(PageSourceImpl.pageExist(ps)) return ps;
694                    return null;
695            }
696        
697        public PageSource[] getRelativePageSources(String realPath) {
698            if(StringUtil.startsWith(realPath,'/')) return getPageSources(realPath);
699            if(pathList.size()==0) return null;
700                    return new PageSource[]{ pathList.getLast().getRealPage(realPath)};
701            }
702        
703        public PageSource getPageSource(String realPath) {
704            SystemOut.print(config.getOutWriter(),"method getPageSource is deprecated");
705            return PageSourceImpl.best(config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true));
706            }
707        
708        public PageSource[] getPageSources(String realPath) {
709            return config.getPageSources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true);
710            }
711        
712        public PageSource getPageSourceExisting(String realPath) {
713            return config.getPageSourceExisting(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,true,false);
714            }
715    
716        public boolean useSpecialMappings(boolean useTagMappings) {
717                    boolean b=this.useSpecialMappings;
718                    this.useSpecialMappings=useTagMappings;
719                    return b;
720            }
721        public boolean useSpecialMappings() {
722                    return useSpecialMappings;
723            }
724        
725        /*public Resource[] getPhysicalResources(String realPath, boolean alsoDefaultMapping) {
726            return config.getPhysicalResources(this,applicationContext.getMappings(),realPath,false,useSpecialMappings,alsoDefaultMapping);
727            }
728        
729        public Resource getPhysicalResourceExisting(String realPath, boolean alsoDefaultMapping) {
730            return config.getPhysicalResourceExisting(this, applicationContext.getMappings(),realPath,false,useSpecialMappings,alsoDefaultMapping);
731            }*/
732        
733        public Resource getPhysical(String realPath, boolean alsoDefaultMapping){
734            return config.getPhysical(applicationContext.getMappings(),realPath, alsoDefaultMapping);
735        }
736        
737    
738            public PageSource toPageSource(Resource res, PageSource defaultValue){
739                    return config.toPageSource(applicationContext.getMappings(),res, defaultValue);
740            }
741    
742            /**
743             * @see railo.runtime.PageContext#doInclude(java.lang.String)
744             */
745            public void doInclude(String realPath) throws PageException {
746                    doInclude(getRelativePageSources(realPath));
747            }
748            
749    
750            public void doInclude(PageSource source) throws PageException {
751                    doInclude(new PageSource[]{source});
752            }
753    
754            /**
755             * @see railo.runtime.PageContext#doInclude(railo.runtime.PageSource)
756             */
757            public void doInclude(PageSource[] sources) throws PageException {
758            // debug
759                    if(config.debug()) {
760                            int currTime=executionTime;
761                long exeTime=0;
762                long time=System.currentTimeMillis();
763                
764                Page currentPage = PageSourceImpl.loadPage(this, sources);
765                //Page currentPage = ((PageSourceImpl)source).loadPage(this,config);
766                            DebugEntry debugEntry=debugger.getEntry(this,currentPage.getPageSource());
767                try {
768                    addPageSource(currentPage.getPageSource(),true);
769                    debugEntry.updateFileLoadTime((int)(System.currentTimeMillis()-time));
770                    exeTime=System.currentTimeMillis();
771                    currentPage.call(this);
772                            }
773                            catch(Throwable t){
774                                    PageException pe = Caster.toPageException(t);
775                                    if(Abort.isAbort(pe)) {
776                        if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe;
777                    }
778                    else {
779                            if(fdEnabled){
780                                    FDSignal.signal(pe, false);
781                            }
782                            pe.addContext(currentPage.getPageSource(),-187,-187, null);// TODO was soll das 187
783                            throw pe;
784                    }
785                            }
786                            finally {
787                                    int diff= ((int)(System.currentTimeMillis()-exeTime)-(executionTime-currTime));
788                                executionTime+=(int)(System.currentTimeMillis()-time);
789                                    debugEntry.updateExeTime(diff);
790                                    removeLastPageSource(true);
791                            }       
792                    }
793            // no debug
794                    else {
795                            PagePlus currentPage = (PagePlus) PageSourceImpl.loadPage(this, sources);
796                            //Page currentPage = ((PageSourceImpl)source).loadPage(this,config);
797                        try {
798                                    addPageSource(currentPage.getPageSource(),true);
799                    currentPage.call(this);
800                            }
801                            catch(Throwable t){
802                                    PageException pe = Caster.toPageException(t);
803                                    if(Abort.isAbort(pe)) {
804                                            if(Abort.isAbort(pe,Abort.SCOPE_REQUEST))throw pe;
805                    }
806                    else    {
807                            pe.addContext(currentPage.getPageSource(),-187,-187, null);
808                            throw pe;
809                    }
810                            }
811                            finally {
812                                    removeLastPageSource(true);
813                            }       
814                    }
815            }
816    
817            /**
818         * @see railo.runtime.PageContext#getTemplatePath()
819         */
820        public Array getTemplatePath() throws ExpressionException {
821            int len=includePathList.size();
822            SVArray sva = new SVArray();
823            PageSource ps;
824            for(int i=0;i<len;i++) {
825                    ps=(PageSource)includePathList.get(i);
826                    if(i==0) {
827                            if(!ps.equals(getBasePageSource()))
828                                    sva.append(ResourceUtil.getResource(this,getBasePageSource()).getAbsolutePath());
829                    }
830                    sva.append(ResourceUtil.getResource(this, ps).getAbsolutePath());
831            }
832            //sva.setPosition(sva.size());
833            return sva;
834        }
835      
836        public List<PageSource> getPageSourceList() {
837            return (List<PageSource>) pathList.clone();
838            
839        }
840        
841        
842        
843        protected PageSource getPageSource(int index) {
844            return (PageSource) includePathList.get(index-1);
845        }
846        public synchronized void copyStateTo(PageContextImpl other) {
847            
848            
849            
850            
851            // private Debugger debugger=new DebuggerImpl();
852            other.requestTimeout=requestTimeout;
853            other.locale=locale;
854            other.timeZone=timeZone;
855            other.fdEnabled=fdEnabled;
856            other.useSpecialMappings=useSpecialMappings;
857            other.serverPassword=serverPassword;
858            
859            
860            hasFamily=true;
861            other.hasFamily=true;
862            other.parent=this;
863                    other.applicationContext=applicationContext;
864                    other.thread=Thread.currentThread();
865                    other.startTime=System.currentTimeMillis();
866            other.isCFCRequest = isCFCRequest;
867            
868            
869            
870            // path
871            other.base=base;
872            java.util.Iterator<PageSource> it = includePathList.iterator();
873            while(it.hasNext()) {
874                    other.includePathList.add(it.next());
875            }
876            it = pathList.iterator();
877            while(it.hasNext()) {
878                    other.pathList.add(it.next());
879            }
880            
881            
882            // scopes
883            //other.req.setAttributes(request);
884            /*HttpServletRequest org = other.req.getOriginalRequest();
885            if(org instanceof HttpServletRequestDummy) {
886                    ((HttpServletRequestDummy)org).setAttributes(request);
887            }*/
888            other.req=req;
889            other.request=request;
890            other.form=form;
891            other.url=url;
892            other.urlForm=urlForm;
893            other._url=_url;
894            other._form=_form;
895            other.variables=variables;
896            other.undefined=new UndefinedImpl(other,(short)other.undefined.getType());
897            
898            // writers
899            other.bodyContentStack.init(other.req,other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(),
900                            other.config.isShowVersion(),config.contentLength(),config.allowCompression());
901            other.writer=other.bodyContentStack.getWriter();
902            other.forceWriter=other.writer;
903            
904            other.psq=psq;
905            other.gatewayContext=gatewayContext;
906            
907            // thread
908            if(threads!=null){
909                    synchronized (threads) {
910                                    
911                            java.util.Iterator it2 = threads.entrySet().iterator();
912                            Map.Entry entry;
913                            while(it2.hasNext()) {
914                                    entry=(Entry) it2.next();
915                                    other.setThreadScope((String)entry.getKey(), (Threads)entry.getValue());
916                            }
917                            }
918            }
919            
920            
921        }
922        
923        /*public static void setState(PageContextImpl other,ApplicationContext applicationContext, boolean isCFCRequest) {
924    
925            other.hasFamily=true;
926            
927                    other.applicationContext=applicationContext;
928                    other.thread=Thread.currentThread();
929                    other.startTime=System.currentTimeMillis();
930            other.isCFCRequest = isCFCRequest;
931            
932            // path
933            other.base=base;
934            java.util.Iterator it = includePathList.iterator();
935            while(it.hasNext()) {
936                    other.includePathList.add(it.next());
937            }
938            
939            // scopes
940            other.request=request;
941            other.form=form;
942            other.url=url;
943            other.urlForm=urlForm;
944            other._url=_url;
945            other._form=_form;
946            other.variables=variables;
947            other.undefined=new UndefinedImpl(other,(short)other.undefined.getType());
948            
949            // writers
950            other.bodyContentStack.init(other.rsp,other.config.isSuppressWhitespace(),other.config.closeConnection(),other.config.isShowVersion());
951            other.writer=other.bodyContentStack.getWriter();
952            other.forceWriter=other.writer;
953            
954            other.psq=psq;
955            }*/
956        
957        public int getCurrentLevel() {
958            return includePathList.size()+1;
959        }
960        
961        /**
962         * @return the current template SourceFile
963         */
964        public PageSource getCurrentPageSource() {
965            return (PageSource) pathList.getLast();
966        }
967        
968        /**
969         * @return the current template SourceFile
970         */
971        public PageSource getCurrentTemplatePageSource() {
972            return (PageSource) includePathList.getLast();
973        }
974            
975        /**
976         * @return base template file
977         */
978        public PageSource getBasePageSource() {
979                    return base;
980            }
981            
982        /**
983         * @see railo.runtime.PageContext#getRootTemplateDirectory()
984         */
985        public Resource getRootTemplateDirectory() {
986                    return config.getResource(servlet.getServletContext().getRealPath("/"));
987                    //new File(servlet.getServletContext().getRealPath("/"));
988            }
989    
990        /**
991         * @see PageContext#scope(int)
992         * @deprecated use instead <code>VariableInterpreter.scope(...)</code>
993         */
994        public Scope scope(int type) throws PageException {
995            switch(type) {
996                case Scope.SCOPE_UNDEFINED:     return undefinedScope();
997                case Scope.SCOPE_URL:           return urlScope();
998                case Scope.SCOPE_FORM:          return formScope();
999                case Scope.SCOPE_VARIABLES:     return variablesScope();
1000                case Scope.SCOPE_REQUEST:       return requestScope();
1001                case Scope.SCOPE_CGI:           return cgiScope();
1002                case Scope.SCOPE_APPLICATION:   return applicationScope();
1003                case Scope.SCOPE_ARGUMENTS:     return argumentsScope();
1004                case Scope.SCOPE_SESSION:       return sessionScope();
1005                case Scope.SCOPE_SERVER:        return serverScope();
1006                case Scope.SCOPE_COOKIE:        return cookieScope();
1007                case Scope.SCOPE_CLIENT:        return clientScope();
1008                case Scope.SCOPE_LOCAL:         
1009                case ScopeSupport.SCOPE_VAR:                return localScope();
1010                case Scope.SCOPE_CLUSTER:return clusterScope();
1011            }
1012            return variables;
1013        }
1014        
1015        public Scope scope(String strScope,Scope defaultValue) throws PageException {
1016            if(strScope==null)return defaultValue;
1017            strScope=strScope.toLowerCase().trim(); 
1018            if("variables".equals(strScope))        return variablesScope(); 
1019            if("url".equals(strScope))                      return urlScope();
1020            if("form".equals(strScope))                     return formScope();
1021            if("request".equals(strScope))          return requestScope();
1022            if("cgi".equals(strScope))                      return cgiScope();
1023            if("application".equals(strScope))      return applicationScope();
1024            if("arguments".equals(strScope))        return argumentsScope();
1025            if("session".equals(strScope))          return sessionScope();
1026            if("server".equals(strScope))           return serverScope();
1027            if("cookie".equals(strScope))           return cookieScope();
1028            if("client".equals(strScope))           return clientScope();
1029            if("local".equals(strScope))            return localScope();
1030            if("cluster".equals(strScope))          return clusterScope();
1031            
1032                return defaultValue;
1033        }
1034        
1035        /**
1036         * @see PageContext#undefinedScope()
1037         */
1038        public Undefined undefinedScope() {
1039            if(!undefined.isInitalized()) undefined.initialize(this);
1040            return undefined;
1041        }
1042        
1043        /**
1044         * @return undefined scope, undefined scope is a placeholder for the scopecascading
1045         */
1046        public Undefined us() {
1047            if(!undefined.isInitalized()) undefined.initialize(this);
1048            return undefined;
1049        }
1050        
1051        /**
1052         * @see PageContext#variablesScope()
1053         */
1054        public Variables variablesScope() { return variables; }
1055            
1056        /**
1057         * @see PageContext#urlScope()
1058         */
1059        public URL urlScope() { 
1060            if(!url.isInitalized())url.initialize(this);
1061                    return url;
1062        }
1063            
1064        /**
1065         * @see PageContext#formScope()
1066         */
1067        public Form formScope() {
1068            if(!form.isInitalized())form.initialize(this);
1069                    return form;
1070        }
1071            
1072        /**
1073         * @see railo.runtime.PageContext#urlFormScope()
1074         */
1075        public URLForm urlFormScope() {
1076            if(!urlForm.isInitalized())urlForm.initialize(this);
1077                    return urlForm;
1078        }
1079    
1080        /**
1081         * @see PageContext#requestScope()
1082         */
1083        public Request requestScope() { return request; }
1084            
1085        /**
1086         * @see PageContext#cgiScope()
1087         */
1088        public CGI cgiScope() {
1089                    if(!cgi.isInitalized())cgi.initialize(this);
1090                    return cgi;
1091            }
1092            
1093        /**
1094         * @see PageContext#applicationScope()
1095         */
1096        public Application applicationScope() throws PageException {
1097                    if(application==null) {
1098                            if(!applicationContext.hasName())
1099                                    throw new ExpressionException("there is no application context defined for this application","you can define a application context with the tag cfapplication");
1100                            application=scopeContext.getApplicationScope(this,DUMMY_BOOL);
1101                    }
1102                    return application; 
1103            }
1104    
1105        /**
1106         * @see PageContext#argumentsScope()
1107         */
1108        public Argument argumentsScope() { return argument; }
1109    
1110        
1111        /**
1112         * @see PageContext#argumentsScope(boolean)
1113         */
1114        public Argument argumentsScope(boolean bind) { 
1115                //Argument a=argumentsScope(); 
1116                if(bind)argument.setBind(true); 
1117                return argument; 
1118        } 
1119        
1120        /**
1121         * @see PageContext#localScope()
1122         */// FUTURE remove class from type Local
1123        public Scope localScope() { 
1124            //if(local==localUnsupportedScope) 
1125            //      throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope"));
1126            return local;
1127        }
1128        
1129    // FUTURE remove class from type Local
1130        public Scope localScope(boolean bind) { 
1131            if(bind)local.setBind(true); 
1132            //if(local==localUnsupportedScope) 
1133            //      throw new PageRuntimeException(new ExpressionException("Unsupported Context for Local Scope"));
1134            return local; 
1135        }
1136    
1137        
1138        public Object localGet() throws PageException { 
1139            return localGet(false);
1140        }
1141        
1142        public Object localGet(boolean bind) throws PageException { 
1143            // inside a local supported block
1144            if(undefined.getCheckArguments()){
1145                    return localScope(bind);
1146            }
1147            return undefinedScope().get(KeyImpl.LOCAL);
1148        }
1149    
1150        public Object localTouch() throws PageException { 
1151            return localTouch(false);
1152        }
1153        
1154        public Object localTouch(boolean bind) throws PageException { 
1155            // inside a local supported block
1156            if(undefined.getCheckArguments()){
1157                    return localScope(bind);
1158            }
1159            return touch(undefinedScope(), KeyImpl.LOCAL);
1160            //return undefinedScope().get(LOCAL);
1161        }
1162        
1163            
1164        /**
1165         * @param local sets the current local scope
1166         * @param argument sets the current argument scope
1167         */
1168        public void setFunctionScopes(Scope local,Argument argument) {
1169            // FUTURE setFunctionScopes(Local local,Argument argument)
1170                    this.argument=argument;
1171                    this.local=(LocalPro) local;
1172                    undefined.setFunctionScopes(local,argument);
1173            }
1174            
1175        /**
1176         * @see PageContext#sessionScope()
1177         */
1178        public Session sessionScope() throws PageException {
1179                    return sessionScope(true);
1180            }
1181        public Session sessionScope(boolean checkExpires) throws PageException {
1182                    if(session==null)       {
1183                            if(!applicationContext.hasName())
1184                                    throw new ExpressionException("there is no session context defined for this application","you can define a session context with the tag cfapplication/Application.cfc");
1185                            if(!applicationContext.isSetSessionManagement())
1186                                    throw new ExpressionException("session scope is not enabled","you can enable session scope with tag cfapplication");
1187                            session=scopeContext.getSessionScope(this,DUMMY_BOOL);
1188                    }
1189                    return session;
1190            }
1191    
1192        /**
1193         * @see PageContext#serverScope()
1194         */
1195        public Server serverScope() { 
1196                    //if(!server.isInitalized()) server.initialize(this);
1197                    return server;
1198            }
1199        
1200        /**
1201         * @see railo.runtime.PageContext#clusterScope()
1202         */
1203        public Cluster clusterScope() throws PageException {
1204            return clusterScope(true);
1205            }
1206        
1207        public Cluster clusterScope(boolean create) throws PageException { 
1208            if(cluster==null && create) {
1209                    cluster=ScopeContext.getClusterScope(config,create);
1210                    //cluster.initialize(this);
1211            }
1212            //else if(!cluster.isInitalized()) cluster.initialize(this);
1213                    return cluster;
1214            }
1215    
1216        /**
1217         * @see PageContext#cookieScope()
1218         */
1219        public Cookie cookieScope() { 
1220            if(!cookie.isInitalized()) cookie.initialize(this);
1221            return cookie;
1222        }
1223            
1224        /**
1225         * @see PageContext#clientScope()
1226         */
1227        public Client clientScope() throws PageException { 
1228                    if(client==null) {
1229                            if(!applicationContext.hasName())
1230                                    throw new ExpressionException("there is no client context defined for this application",
1231                                                    "you can define a client context with the tag cfapplication/Application.cfc");
1232                            if(!applicationContext.isSetClientManagement())
1233                                    throw new ExpressionException("client scope is not enabled",
1234                                                    "you can enable client scope with tag cfapplication/Application.cfc");
1235                            
1236                            client=(ClientPlus) scopeContext.getClientScope(this);
1237                    }
1238                    return client;
1239            }
1240        
1241        public Client clientScopeEL() { 
1242                    if(client==null) {
1243                            if(!applicationContext.hasName())                               return null;
1244                            if(!applicationContext.isSetClientManagement()) return null;
1245                            client=(ClientPlus) scopeContext.getClientScopeEL(this);
1246                    }
1247                    return client;
1248            }
1249            
1250        /**
1251         * @see PageContext#set(java.lang.Object, java.lang.String, java.lang.Object)
1252         */
1253        public Object set(Object coll, String key, Object value) throws PageException {
1254                return variableUtil.set(this,coll,key,value);
1255            }
1256    
1257            public Object set(Object coll, Collection.Key key, Object value) throws PageException {
1258                    return variableUtil.set(this,coll,key,value);
1259            }
1260            
1261        /**
1262         * @see PageContext#touch(java.lang.Object, java.lang.String)
1263         */
1264        public Object touch(Object coll, String key) throws PageException {
1265                Object o=getCollection(coll,key,null);
1266                if(o!=null) return o;
1267                return set(coll,key,new StructImpl());
1268            } 
1269    
1270            /**
1271             *
1272             * @see railo.runtime.PageContext#touch(java.lang.Object, railo.runtime.type.Collection.Key)
1273             */
1274            public Object touch(Object coll, Collection.Key key) throws PageException {
1275                    Object o=getCollection(coll,key,null);
1276                if(o!=null) return o;
1277                return set(coll,key,new StructImpl());
1278            }
1279        
1280        /*private Object _touch(Scope scope, String key) throws PageException {
1281                Object o=scope.get(key,null);
1282                if(o!=null) return o;
1283                return scope.set(key, new StructImpl());
1284            }*/     
1285        
1286    
1287        
1288        
1289    
1290        /**
1291         * @see PageContext#getCollection(java.lang.Object, java.lang.String)
1292         */
1293        public Object getCollection(Object coll, String key) throws PageException {
1294            return variableUtil.getCollection(this,coll,key);
1295            }
1296    
1297            /**
1298             * @see railo.runtime.PageContext#getCollection(java.lang.Object, railo.runtime.type.Collection.Key)
1299             */
1300            public Object getCollection(Object coll, Collection.Key key) throws PageException {
1301                    return variableUtil.getCollection(this,coll,key);
1302            }
1303            
1304        /**
1305         *
1306         * @see railo.runtime.PageContext#getCollection(java.lang.Object, java.lang.String, java.lang.Object)
1307         */
1308        public Object getCollection(Object coll, String key, Object defaultValue) {
1309                    return variableUtil.getCollection(this,coll,key,defaultValue);
1310            }
1311    
1312            /**
1313             * @see railo.runtime.PageContext#getCollection(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object)
1314             */
1315            public Object getCollection(Object coll, Collection.Key key, Object defaultValue) {
1316                    return variableUtil.getCollection(this,coll,key,defaultValue);
1317            }
1318            
1319        /**
1320         * @see PageContext#get(java.lang.Object, java.lang.String)
1321         */
1322        public Object get(Object coll, String key) throws PageException {
1323                    return variableUtil.get(this,coll,key);
1324            }
1325    
1326            /**
1327             *
1328             * @see railo.runtime.PageContext#get(java.lang.Object, railo.runtime.type.Collection.Key)
1329             */
1330            public Object get(Object coll, Collection.Key key) throws PageException {
1331                    return variableUtil.get(this,coll,key);
1332            }
1333            
1334        /**
1335         *
1336         * @see railo.runtime.PageContext#getReference(java.lang.Object, java.lang.String)
1337         */
1338        public Reference getReference(Object coll, String key) throws PageException {
1339                    return new VariableReference(coll,key);
1340            }
1341    
1342            public Reference getReference(Object coll, Collection.Key key) throws PageException {
1343                    return new VariableReference(coll,key);
1344            }
1345    
1346        /**
1347         * @see railo.runtime.PageContext#get(java.lang.Object, java.lang.String, java.lang.Object)
1348         */
1349        public Object get(Object coll, String key, Object defaultValue) {
1350            return variableUtil.get(this,coll,key, defaultValue);
1351        }
1352    
1353            /**
1354             * @see railo.runtime.PageContext#get(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object)
1355             */
1356            public Object get(Object coll, Collection.Key key, Object defaultValue) {
1357                    return variableUtil.get(this,coll,key, defaultValue);
1358            }
1359            
1360        /**
1361         * @see PageContext#setVariable(java.lang.String, java.lang.Object)
1362         */
1363        public Object setVariable(String var, Object value) throws PageException {
1364                //return new CFMLExprInterpreter().interpretReference(this,new ParserString(var)).set(value);
1365                return VariableInterpreter.setVariable(this,var,value);
1366            }
1367        
1368        /**
1369         * @see PageContext#getVariable(java.lang.String)
1370         */
1371        public Object getVariable(String var) throws PageException {
1372                    return VariableInterpreter.getVariable(this,var);
1373            }
1374        
1375    
1376        public void param(String type, String name, Object defaultValue,String regex) throws PageException {
1377            param(type, name, defaultValue,Double.NaN,Double.NaN,regex);
1378        }
1379            public void param(String type, String name, Object defaultValue,double min, double max) throws PageException {
1380            param(type, name, defaultValue,min,max,null);
1381        }
1382    
1383        public void param(String type, String name, Object defaultValue) throws PageException {
1384            param(type, name, defaultValue,Double.NaN,Double.NaN,null);
1385        }
1386            
1387        private void param(String type, String name, Object defaultValue, double min,double max, String strPattern) throws PageException {
1388                    
1389            
1390            // check attributes type
1391            if(type==null)type="any";
1392                    else type=type.trim().toLowerCase();
1393    
1394            // check attributes name
1395            if(StringUtil.isEmpty(name))
1396                            throw new ExpressionException("The attribute name is required");
1397            
1398            Object value=null;
1399                    boolean isNew=false;
1400                    // get value
1401                    try {
1402                            value=getVariable(name);
1403                    } 
1404                    catch (PageException e) {
1405                            if(defaultValue==null)
1406                                    throw new ExpressionException("The required parameter ["+name+"] was not provided.");
1407                            value=defaultValue;
1408                            isNew=true;
1409                    }
1410                    // cast and set value
1411                    if(!"any".equals(type)) {
1412                            // range
1413                            if("range".equals(type)) {
1414                                    double number = Caster.toDoubleValue(value);
1415                                    if(!Decision.isValid(min)) throw new ExpressionException("Missing attribute [min]");
1416                                    if(!Decision.isValid(max)) throw new ExpressionException("Missing attribute [max]");
1417                                    if(number<min || number>max)
1418                                            throw new ExpressionException("The number ["+Caster.toString(number)+"] is out of range [min:"+Caster.toString(min)+";max:"+Caster.toString(max)+"]");
1419                                    setVariable(name,Caster.toDouble(number));
1420                            }
1421                            // regex
1422                            else if("regex".equals(type) || "regular_expression".equals(type)) {
1423                                    String str=Caster.toString(value);
1424                                    
1425                                    if(strPattern==null) throw new ExpressionException("Missing attribute [pattern]");
1426                                    
1427                                    try {
1428                                            Pattern pattern = new Perl5Compiler().compile(strPattern, Perl5Compiler.DEFAULT_MASK);
1429                                    PatternMatcherInput input = new PatternMatcherInput(str);
1430                                    if( !new Perl5Matcher().matches(input, pattern))
1431                                            throw new ExpressionException("The value ["+str+"] doesn't match the provided pattern ["+strPattern+"]");
1432                                    
1433                                    } catch (MalformedPatternException e) {
1434                                            throw new ExpressionException("The provided pattern ["+strPattern+"] is invalid",e.getMessage());
1435                                    }
1436                                    setVariable(name,str);
1437                            }
1438                            else {
1439                                    if(!Decision.isCastableTo(type,value,true)) throw new CasterException(value,type);      
1440                                    setVariable(name,value);
1441                                    //REALCAST setVariable(name,Caster.castTo(this,type,value,true));
1442                            }
1443                    }
1444                else if(isNew) setVariable(name,value);
1445            }
1446        
1447        
1448        
1449        
1450            
1451        /**
1452         * @see PageContext#removeVariable(java.lang.String)
1453         */
1454        public Object removeVariable(String var) throws PageException {
1455                    return VariableInterpreter.removeVariable(this,var);
1456            }
1457    
1458        /**
1459         * 
1460         * a variable reference, references to variable, to modifed it, with global effect.
1461         * @param var variable name to get
1462         * @return return a variable reference by string syntax ("scopename.key.key" -> "url.name")
1463         * @throws PageException
1464         */
1465        public VariableReference getVariableReference(String var) throws PageException { 
1466                return VariableInterpreter.getVariableReference(this,var);
1467            } 
1468            
1469        /**
1470         * @see railo.runtime.PageContext#getFunction(java.lang.Object, java.lang.String, java.lang.Object[])
1471         */
1472        public Object getFunction(Object coll, String key, Object[] args) throws PageException {
1473            return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args);
1474            }
1475    
1476            /**
1477             * @see railo.runtime.PageContext#getFunction(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object[])
1478             */
1479            public Object getFunction(Object coll, Key key, Object[] args) throws PageException {
1480                    return variableUtil.callFunctionWithoutNamedValues(this,coll,key,args);
1481            }
1482            
1483        /**
1484         * @see railo.runtime.PageContext#getFunctionWithNamedValues(java.lang.Object, java.lang.String, java.lang.Object[])
1485         */
1486        public Object getFunctionWithNamedValues(Object coll, String key, Object[] args) throws PageException {
1487                    return variableUtil.callFunctionWithNamedValues(this,coll,key,args);
1488            }
1489    
1490            /**
1491             *
1492             * @see railo.runtime.PageContext#getFunctionWithNamedValues(java.lang.Object, railo.runtime.type.Collection.Key, java.lang.Object[])
1493             */
1494            public Object getFunctionWithNamedValues(Object coll, Key key, Object[] args) throws PageException {
1495                    return variableUtil.callFunctionWithNamedValues(this,coll,key,args);
1496            }
1497    
1498        /**
1499         * @see railo.runtime.PageContext#getConfig()
1500         */
1501        public ConfigWeb getConfig() {
1502            return config;
1503        }
1504        
1505        /**
1506         * @see railo.runtime.PageContext#getIterator(java.lang.String)
1507         */
1508        public Iterator getIterator(String key) throws PageException {
1509                    Object o=VariableInterpreter.getVariable(this,key);
1510                    if(o instanceof Iterator) return (Iterator) o;
1511                    throw new ExpressionException("["+key+"] is not a iterator object");
1512            }
1513    
1514        /**
1515         * @see PageContext#getQuery(java.lang.String)
1516         */
1517        public Query getQuery(String key) throws PageException {
1518                    Object o=VariableInterpreter.getVariable(this,key);
1519                    if(o instanceof Query) return (Query) o;
1520                    throw new CasterException(o,Query.class);///("["+key+"] is not a query object, object is from type ");
1521            }
1522    
1523            /**
1524             * @see javax.servlet.jsp.PageContext#setAttribute(java.lang.String, java.lang.Object)
1525             */
1526            public void setAttribute(String name, Object value) {
1527                try {
1528                if(value==null)removeVariable(name);
1529                else setVariable(name,value);
1530            } catch (PageException e) {}
1531            }
1532    
1533            /**
1534             * @see javax.servlet.jsp.PageContext#setAttribute(java.lang.String, java.lang.Object, int)
1535             */
1536            public void setAttribute(String name, Object value, int scope) {
1537                    switch(scope){
1538                    case javax.servlet.jsp.PageContext.APPLICATION_SCOPE:
1539                            if(value==null) getServletContext().removeAttribute(name);
1540                            else getServletContext().setAttribute(name, value);
1541                    break;
1542                    case javax.servlet.jsp.PageContext.PAGE_SCOPE:
1543                            setAttribute(name, value);
1544                    break;
1545                    case javax.servlet.jsp.PageContext.REQUEST_SCOPE:
1546                            if(value==null) req.removeAttribute(name);
1547                            else setAttribute(name, value);
1548                    break;
1549                    case javax.servlet.jsp.PageContext.SESSION_SCOPE:
1550                            HttpSession s = req.getSession(true);
1551                            if(value==null)s.removeAttribute(name);
1552                            else s.setAttribute(name, value);
1553                    break;
1554                    }       
1555            }
1556    
1557            /**
1558             * @see javax.servlet.jsp.PageContext#getAttribute(java.lang.String)
1559             */
1560            public Object getAttribute(String name) {
1561                    try {
1562                            return getVariable(name);
1563                    } catch (PageException e) {
1564                            return null;
1565                    }
1566            }
1567    
1568            /**
1569             * @see javax.servlet.jsp.PageContext#getAttribute(java.lang.String, int)
1570             */
1571            public Object getAttribute(String name, int scope) {
1572                    switch(scope){
1573                    case javax.servlet.jsp.PageContext.APPLICATION_SCOPE:
1574                            return getServletContext().getAttribute(name);
1575                    case javax.servlet.jsp.PageContext.PAGE_SCOPE:
1576                            return getAttribute(name);
1577                    case javax.servlet.jsp.PageContext.REQUEST_SCOPE:
1578                            return req.getAttribute(name);
1579                    case javax.servlet.jsp.PageContext.SESSION_SCOPE:
1580                            HttpSession s = req.getSession();
1581                            if(s!=null)return s.getAttribute(name);
1582                    break;
1583                    }       
1584                    return null;
1585            }
1586    
1587            /**
1588             * @see javax.servlet.jsp.PageContext#findAttribute(java.lang.String)
1589             */
1590            public Object findAttribute(String name) {
1591                    // page
1592                    Object value=getAttribute(name);
1593                    if(value!=null) return value;
1594                    // request
1595                    value=req.getAttribute(name);
1596                    if(value!=null) return value;
1597                    // session
1598                    HttpSession s = req.getSession();
1599                    value=s!=null?s.getAttribute(name):null;
1600                    if(value!=null) return value;
1601                    // application
1602                    value=getServletContext().getAttribute(name);
1603                    if(value!=null) return value;
1604                    
1605                    
1606                    return null;
1607            }
1608    
1609            /**
1610             * @see javax.servlet.jsp.PageContext#removeAttribute(java.lang.String)
1611             */
1612            public void removeAttribute(String name) {
1613                    setAttribute(name, null);
1614            }
1615    
1616            /**
1617             * @see javax.servlet.jsp.PageContext#removeAttribute(java.lang.String, int)
1618             */
1619            public void removeAttribute(String name, int scope) {
1620                    setAttribute(name, null,scope);
1621            }
1622    
1623            /**
1624             * @see javax.servlet.jsp.PageContext#getAttributesScope(java.lang.String)
1625             */
1626            public int getAttributesScope(String name) {
1627                    // page
1628                    if(getAttribute(name)!=null) return PageContext.PAGE_SCOPE;
1629            // request
1630            if(req.getAttribute(name) != null) return PageContext.REQUEST_SCOPE;
1631            // session
1632            HttpSession s = req.getSession();
1633            if(s!=null && s.getAttribute(name) != null) return PageContext.SESSION_SCOPE;
1634            // application
1635            if(getServletContext().getAttribute(name)!=null) return PageContext.APPLICATION_SCOPE;
1636            
1637                    return 0;
1638            }
1639    
1640            /**
1641             * @see javax.servlet.jsp.PageContext#getAttributeNamesInScope(int)
1642             */
1643            public Enumeration getAttributeNamesInScope(int scope) {
1644                    
1645            switch(scope){
1646                    case javax.servlet.jsp.PageContext.APPLICATION_SCOPE:
1647                            return getServletContext().getAttributeNames();
1648                    case javax.servlet.jsp.PageContext.PAGE_SCOPE:
1649                            return new KeyIterator(variablesScope().keys());
1650                    case javax.servlet.jsp.PageContext.REQUEST_SCOPE:
1651                            return req.getAttributeNames();
1652                    case javax.servlet.jsp.PageContext.SESSION_SCOPE:
1653                            return req.getSession(true).getAttributeNames();
1654                    }
1655                    return null;
1656            }
1657    
1658            /**
1659             * @see javax.servlet.jsp.PageContext#getOut()
1660             */
1661            public JspWriter getOut() {
1662                    return forceWriter;
1663            }
1664    
1665            /**
1666             * @see javax.servlet.jsp.PageContext#getSession()
1667             */
1668            public HttpSession getSession() {
1669                    return getHttpServletRequest().getSession();
1670            }
1671    
1672            /**
1673             * @see javax.servlet.jsp.PageContext#getPage()
1674             */
1675            public Object getPage() {
1676                    return variablesScope();
1677            }
1678    
1679            /**
1680             * @see javax.servlet.jsp.PageContext#getRequest()
1681             */
1682            public ServletRequest getRequest() {
1683                    return getHttpServletRequest();
1684            }
1685            
1686        /**
1687         * @see railo.runtime.PageContext#getHttpServletRequest()
1688         */
1689        public HttpServletRequest getHttpServletRequest() {
1690                    return req;
1691            }
1692    
1693            /**
1694             * @see javax.servlet.jsp.PageContext#getResponse()
1695             */
1696            public ServletResponse getResponse() {
1697                    return rsp;
1698            }
1699    
1700        /**
1701         * @see railo.runtime.PageContext#getHttpServletResponse()
1702         */
1703        public HttpServletResponse getHttpServletResponse() {
1704                    return rsp;
1705            }
1706        
1707        public ServletOutputStream getServletOutputStream() throws IOException {// FUTURE remove from interface
1708            throw new RuntimeException("not supported");
1709            }
1710        
1711        public OutputStream getResponseStream() throws IOException {// FUTURE add to  interface
1712            return getRootOut().getResponseStream();
1713            }
1714    
1715            /**
1716             * @see javax.servlet.jsp.PageContext#getException()
1717             */
1718            public Exception getException() {
1719                    // TODO impl
1720                    return exception;
1721            }
1722    
1723            /**
1724             * @see javax.servlet.jsp.PageContext#getServletConfig()
1725             */
1726            public ServletConfig getServletConfig() {
1727                    return config;
1728            }
1729    
1730            /**
1731             * @see javax.servlet.jsp.PageContext#getServletContext()
1732             */
1733            public ServletContext getServletContext() {
1734                    return servlet.getServletContext();
1735            }
1736    
1737            /*public static void main(String[] args) {
1738                    repl(" susi #error.susi# sorglos","susi", "Susanne");
1739                    repl(" susi #error.Susi# sorglos","susi", "Susanne");
1740            }*/
1741            private static String repl(String haystack, String needle, String replacement) {
1742                    //print.o("------------");
1743                    //print.o(haystack);
1744                    //print.o(needle);
1745                    StringBuilder regex=new StringBuilder("#[\\s]*error[\\s]*\\.[\\s]*");
1746                    
1747                    char[] carr = needle.toCharArray();
1748                    for(int i=0;i<carr.length;i++){
1749                            regex.append("[");
1750                            regex.append(Character.toLowerCase(carr[i]));
1751                            regex.append(Character.toUpperCase(carr[i]));
1752                            regex.append("]");
1753                    }
1754                    
1755                    
1756                    regex.append("[\\s]*#");
1757                    //print.o(regex);
1758                    
1759                    
1760                    haystack=haystack.replaceAll(regex.toString(), replacement);
1761                    //print.o(haystack);
1762                    return haystack;
1763            }
1764            
1765            
1766            /**
1767             * @see railo.runtime.PageContext#handlePageException(railo.runtime.exp.PageException)
1768             */
1769            public void handlePageException(PageException pe) {
1770                    if(!Abort.isSilentAbort(pe)) {
1771                            
1772                            String charEnc = rsp.getCharacterEncoding();
1773                    if(StringUtil.isEmpty(charEnc,true)) {
1774                                    rsp.setContentType("text/html");
1775                    }
1776                    else {
1777                            rsp.setContentType("text/html; charset=" + charEnc);
1778                    }
1779                            
1780                            int statusCode=getStatusCode(pe);
1781                            
1782                            if(getConfig().getErrorStatusCode())rsp.setStatus(statusCode);
1783                            
1784                            ErrorPage ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_EXCEPTION);
1785                            
1786                            ExceptionHandler.printStackTrace(this,pe);
1787                            ExceptionHandler.log(getConfig(),pe);
1788                            // error page exception
1789                            if(ep!=null) {
1790                                    try {
1791                                            Struct sct=pe.getErrorBlock(this,ep);
1792                                            variablesScope().setEL(ERROR,sct);
1793                                            variablesScope().setEL(CFERROR,sct);
1794                                            
1795                                            doInclude(ep.getTemplate());
1796                                            return;
1797                                    } catch (Throwable t) {
1798                                            if(Abort.isSilentAbort(t)) return;
1799                                            pe=Caster.toPageException(t);
1800                                    }
1801                                    
1802                            }
1803                            
1804                            // error page request
1805                            
1806                            ep=errorPagePool.getErrorPage(pe,ErrorPageImpl.TYPE_REQUEST);
1807                            if(ep!=null) {
1808                                    PageSource ps = ep.getTemplate();
1809                                    if(ps.physcalExists()){
1810                                            Resource res = ps.getFile();
1811                                            try {
1812                                                    String content = IOUtil.toString(res, getConfig().getTemplateCharset());
1813                                                    Struct sct=pe.getErrorBlock(this,ep);
1814                                                    Key[] keys = sct.keys();
1815                                                    String v;
1816                                                    for(int i=0;i<keys.length;i++){
1817                                                            v=Caster.toString(sct.get(keys[i],null),null);
1818                                                            if(v!=null)content=repl(content, keys[i].getString(), v);
1819                                                    }
1820                                                    
1821                                                    write(content);
1822                                                    return;
1823                                            } catch (Throwable t) {
1824                                                    pe=Caster.toPageException(t);
1825                                                    
1826                                            }
1827                                            
1828                                    }
1829                                    else pe=new ApplicationException("The error page template for type request only works if the actual source file also exists . If the exception file is in an Railo archive (.rc/.rcs), you need to use type exception instead.");
1830                            }
1831                            
1832                            
1833                            try {
1834                                    if(statusCode!=404)
1835                                            forceWrite("<!-- Railo ["+Info.getVersionAsString()+"] Error -->");
1836                                    
1837                                    String template=getConfig().getErrorTemplate(statusCode);
1838                                    if(!StringUtil.isEmpty(template)) {
1839                                            try {
1840                                                    Struct catchBlock=pe.getCatchBlock(this);
1841                                                    variablesScope().setEL(CFCATCH,catchBlock);
1842                                                    variablesScope().setEL(CATCH,catchBlock);
1843                                                    doInclude(template);
1844                                                return;
1845                                    } 
1846                                            catch (PageException e) {
1847                                                    pe=e;
1848                                            }
1849                                    }
1850                                    if(!Abort.isSilentAbort(pe))forceWrite(getConfig().getDefaultDumpWriter().toString(this,pe.toDumpData(this, 9999,DumpUtil.toDumpProperties()),true));
1851                            } 
1852                            catch (Exception e) { 
1853                            }
1854                    }
1855            }
1856    
1857            private int getStatusCode(PageException pe) {
1858                    int statusCode=500;
1859                    int maxDeepFor404=0;
1860                    if(pe instanceof ModernAppListenerException){
1861                            pe=((ModernAppListenerException)pe).getPageException();
1862                            maxDeepFor404=1;
1863                    }
1864                    else if(pe instanceof PageExceptionBox)
1865                            pe=((PageExceptionBox)pe).getPageException();
1866                    
1867                    if(pe instanceof MissingIncludeException) {
1868                            MissingIncludeException mie=(MissingIncludeException) pe;
1869                            if(mie.getPageDeep()<=maxDeepFor404) statusCode=404;
1870                    }
1871                    
1872                    // TODO Auto-generated method stub
1873                    return statusCode;
1874            }
1875    
1876    
1877            /**
1878             * @see javax.servlet.jsp.PageContext#handlePageException(java.lang.Exception)
1879             */
1880            public void handlePageException(Exception e) {
1881                    handlePageException(Caster.toPageException(e));         
1882            }
1883    
1884            /**
1885             * @see javax.servlet.jsp.PageContext#handlePageException(java.lang.Throwable)
1886             */
1887            public void handlePageException(Throwable t) {
1888            handlePageException(Caster.toPageException(t));
1889            }
1890    
1891        /**
1892         * @see PageContext#setHeader(java.lang.String, java.lang.String)
1893         */
1894        public void setHeader(String name, String value) {
1895                    rsp.setHeader(name,value);
1896            }
1897    
1898            /**
1899             * @see javax.servlet.jsp.PageContext#pushBody()
1900             */
1901            public BodyContent pushBody() {
1902            forceWriter=bodyContentStack.push();
1903            if(enablecfoutputonly>0 && outputState==0) {
1904                writer=devNull;
1905            }
1906            else writer=forceWriter;
1907            return (BodyContent)forceWriter;
1908            }
1909    
1910            /**
1911             * @see javax.servlet.jsp.PageContext#popBody()
1912             */
1913            public JspWriter popBody() {
1914            forceWriter=bodyContentStack.pop();
1915            if(enablecfoutputonly>0 && outputState==0) {
1916                writer=devNull;
1917            }
1918            else writer=forceWriter;
1919            return forceWriter;
1920            }
1921    
1922        /**
1923         * @see railo.runtime.PageContext#outputStart()
1924         */
1925        public void outputStart() {
1926                    outputState++;
1927            if(enablecfoutputonly>0 && outputState==1)writer=forceWriter;
1928                    //if(enablecfoutputonly && outputState>0) unsetDevNull();
1929            }
1930    
1931        /**
1932         * @see railo.runtime.PageContext#outputEnd()
1933         */
1934        public void outputEnd() {
1935                    outputState--;
1936                    if(enablecfoutputonly>0 && outputState==0)writer=devNull;
1937            }
1938    
1939        /**
1940         * @see railo.runtime.PageContext#setCFOutputOnly(boolean)
1941         */
1942        public void setCFOutputOnly(boolean boolEnablecfoutputonly) {
1943            if(boolEnablecfoutputonly)this.enablecfoutputonly++;
1944            else if(this.enablecfoutputonly>0)this.enablecfoutputonly--;
1945            setCFOutputOnly(enablecfoutputonly);
1946            //if(!boolEnablecfoutputonly)setCFOutputOnly(enablecfoutputonly=0);
1947        }
1948    
1949        /**
1950         * @see railo.runtime.PageContext#setCFOutputOnly(short)
1951         */
1952        public void setCFOutputOnly(short enablecfoutputonly) {
1953            this.enablecfoutputonly=enablecfoutputonly;
1954            if(enablecfoutputonly>0) {
1955                if(outputState==0) writer=devNull;
1956            }
1957            else {
1958                writer=forceWriter;
1959            }
1960        }
1961    
1962        /**
1963         * @see railo.runtime.PageContext#setSilent()
1964         */
1965        public boolean setSilent() {
1966            boolean before=bodyContentStack.getDevNull();
1967                    bodyContentStack.setDevNull(true);
1968                    
1969            forceWriter = bodyContentStack.getWriter();
1970            writer=forceWriter;
1971            return before;
1972            }
1973            
1974        /**
1975         * @see railo.runtime.PageContext#unsetSilent()
1976         */
1977        public boolean unsetSilent() {
1978            boolean before=bodyContentStack.getDevNull();
1979            bodyContentStack.setDevNull(false);
1980            
1981            forceWriter = bodyContentStack.getWriter();
1982            if(enablecfoutputonly>0 && outputState==0) {
1983                writer=devNull;
1984            }
1985            else writer=forceWriter;
1986            return before;
1987            }
1988        
1989        /**
1990         * @see railo.runtime.PageContext#getDebugger()
1991         */
1992        public Debugger getDebugger() {
1993                    return debugger;
1994            }
1995            
1996        /**
1997         * @throws PageException 
1998         * @see railo.runtime.PageContext#execute(java.lang.String)
1999         */
2000    
2001        public void execute(String realPath, boolean throwExcpetion) throws PageException  {
2002            execute(realPath, throwExcpetion, true);
2003        }
2004        public void execute(String realPath, boolean throwExcpetion, boolean onlyTopLevel) throws PageException  {
2005            SystemOut.printDate(config.getOutWriter(),"Call:"+realPath+" ("+getId()+")");
2006                ApplicationListener listener=config.getApplicationListener();
2007                if(realPath.startsWith("/mapping-")){
2008                    base=null;
2009                    int index = realPath.indexOf('/',9);
2010                    if(index>-1){
2011                            String type = realPath.substring(9,index);
2012                            if(type.equalsIgnoreCase("tag")){
2013                                    base=getPageSource(
2014                                                    new Mapping[]{config.getTagMapping(),config.getServerTagMapping()},
2015                                                    realPath.substring(index)
2016                                                    );
2017                            }
2018                            else if(type.equalsIgnoreCase("customtag")){
2019                                    base=getPageSource(
2020                                                    config.getCustomTagMappings(),
2021                                                    realPath.substring(index)
2022                                                    );
2023                            }
2024                            /*else if(type.equalsIgnoreCase("gateway")){
2025                                    base=config.getGatewayEngine().getMapping().getPageSource(realPath.substring(index));
2026                                    if(!base.exists())base=getPageSource(realPath.substring(index));
2027                            }*/
2028                    }
2029                    if(base==null) base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true));
2030                    
2031                }
2032                else base=PageSourceImpl.best(config.getPageSources(this,null,realPath,onlyTopLevel,false,true));
2033                
2034                try {
2035                    listener.onRequest(this,base);
2036                    log(false);
2037                }
2038                catch(Throwable t) {
2039                    PageException pe = Caster.toPageException(t);
2040                    if(!Abort.isSilentAbort(pe)){
2041                            log(true);
2042                            if(fdEnabled){
2043                                    FDSignal.signal(pe, false);
2044                            }
2045                            listener.onError(this,pe);      
2046                    }
2047                    else log(false);
2048                    if(throwExcpetion) throw pe;
2049                }
2050                finally {
2051                if(enablecfoutputonly>0){
2052                    setCFOutputOnly((short)0);
2053                }
2054                if(getConfig().debug()) {
2055                    try {
2056                                            listener.onDebug(this);
2057                                    } 
2058                    catch (PageException pe) {
2059                            if(!Abort.isSilentAbort(pe))listener.onError(this,pe);
2060                                    }
2061                }
2062                base=null;
2063                }
2064            }
2065            
2066            private void log(boolean error) {
2067                    if(!isGatewayContext() && config.isMonitoringEnabled()) {
2068                RequestMonitor[] monitors = config.getRequestMonitors();
2069                if(monitors!=null)for(int i=0;i<monitors.length;i++){
2070                    if(monitors[i].isLogEnabled()){
2071                            try {
2072                                    monitors[i].log(this,error);
2073                                    } 
2074                                    catch (Throwable e) {}
2075                        }
2076                }
2077                    }
2078            }
2079    
2080    
2081    
2082            private PageSource getPageSource(Mapping[] mappings, String realPath) {
2083                    PageSource ps;
2084                    //print.err(mappings.length);
2085            for(int i=0;i<mappings.length;i++) {
2086                ps = mappings[i].getPageSource(realPath);
2087                //print.err(ps.getDisplayPath());
2088                if(ps.exists()) return ps;
2089                
2090            }
2091                    return null;
2092            }
2093    
2094    
2095    
2096            /**
2097             * @see javax.servlet.jsp.PageContext#include(java.lang.String)
2098             */
2099            public void include(String realPath) throws ServletException,IOException  {
2100                    HTTPUtil.include(this, realPath);
2101            }
2102            
2103    
2104            /**
2105             * @see javax.servlet.jsp.PageContext#forward(java.lang.String)
2106             */
2107            public void forward(String realPath) throws ServletException, IOException {
2108                    HTTPUtil.forward(this, realPath);
2109            }
2110    
2111            /**
2112             * @see railo.runtime.PageContext#include(railo.runtime.PageSource)
2113             */
2114            public void include(PageSource ps) throws ServletException  {
2115                    try {
2116                            doInclude(ps);
2117                    } catch (PageException pe) {
2118                            throw new PageServletException(pe);
2119                    }
2120            }
2121    
2122        /**
2123         * @see railo.runtime.PageContext#clear()
2124         */
2125        public void clear() {
2126                    try {
2127                            //print.o(getOut().getClass().getName());
2128                            getOut().clear();
2129                    } catch (IOException e) {}
2130            }
2131            
2132        /**
2133         * @see railo.runtime.PageContext#getRequestTimeout()
2134         */
2135        public long getRequestTimeout() {
2136                    if(requestTimeout==-1)
2137                            requestTimeout=config.getRequestTimeout().getMillis();
2138                    return requestTimeout;
2139            }
2140            
2141        /**
2142         * @see railo.runtime.PageContext#setRequestTimeout(long)
2143         */
2144        public void setRequestTimeout(long requestTimeout) {
2145                    this.requestTimeout = requestTimeout;
2146            }
2147    
2148        /**
2149         * @see PageContext#getCFID()
2150         */
2151        public String getCFID() {
2152                    if(cfid==null) initIdAndToken();
2153                    return cfid;
2154            }
2155    
2156        /**
2157         * @see PageContext#getCFToken()
2158         */
2159        public String getCFToken() {
2160                    if(cftoken==null) initIdAndToken();
2161                    return cftoken;
2162            }
2163    
2164        /**
2165         * @see PageContext#getURLToken()
2166         */
2167        public String getURLToken() {
2168                if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) {
2169                    HttpSession s = getSession();
2170                        return "CFID="+getCFID()+"&CFTOKEN="+getCFToken()+"&jsessionid="+(s!=null?getSession().getId():"");
2171                    }
2172                    return "CFID="+getCFID()+"&CFTOKEN="+getCFToken();
2173            }
2174        
2175        /**
2176         * @see railo.runtime.PageContext#getJSessionId()
2177         */
2178        public String getJSessionId() {
2179                if(getConfig().getSessionType()==Config.SESSION_TYPE_J2EE) {
2180                        return getSession().getId();
2181                    }
2182                    return null;
2183            }
2184    
2185        /**
2186         * initialize the cfid and the cftoken
2187         */
2188        private void initIdAndToken() {
2189            boolean setCookie=true;
2190            // From URL
2191            Object oCfid = urlScope().get(KeyImpl.CFID,null);
2192            Object oCftoken = urlScope().get(KeyImpl.CFTOKEN,null);
2193            // Cookie
2194            if((oCfid==null || !Decision.isGUIdSimple(oCfid)) || oCftoken==null) {
2195                setCookie=false;
2196                oCfid = cookieScope().get(KeyImpl.CFID,null);
2197                oCftoken = cookieScope().get(KeyImpl.CFTOKEN,null);
2198            }
2199            if(oCfid!=null && !Decision.isGUIdSimple(oCfid) ) {
2200                    oCfid=null;
2201            }
2202            // New One
2203            if(oCfid==null || oCftoken==null) {
2204                setCookie=true;
2205                cfid=ScopeContext.getNewCFId();
2206                cftoken=ScopeContext.getNewCFToken();
2207            }
2208            else {
2209                cfid=Caster.toString(oCfid,null);
2210                cftoken=Caster.toString(oCftoken,null);
2211            }
2212            
2213            if(setCookie && applicationContext.isSetClientCookies()) {
2214                cookieScope().setCookieEL(KeyImpl.CFID,cfid,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(CGIImpl.SERVER_NAME,null):null);
2215                cookieScope().setCookieEL(KeyImpl.CFTOKEN,cftoken,CookieImpl.NEVER,false,"/",applicationContext.isSetDomainCookies()?(String) cgiScope().get(CGIImpl.SERVER_NAME,null):null);
2216            }
2217        }
2218    
2219        /**
2220         * @see PageContext#getId()
2221         */
2222        public int getId() {
2223                    return id;
2224            }
2225    
2226        /**
2227         * @return returns the root JSP Writer
2228         * 
2229         */
2230        public CFMLWriter getRootOut() {
2231                    return bodyContentStack.getBase();
2232            }
2233    
2234        /**
2235         * @see PageContext#getLocale()
2236         */
2237        public Locale getLocale() {
2238                    if(locale==null) locale=config.getLocale();
2239                    return locale;
2240            }
2241    
2242        /**
2243         * @see railo.runtime.PageContext#setPsq(boolean)
2244         */
2245        public void setPsq(boolean psq) {
2246                    this.psq=psq;
2247            }
2248            
2249        /**
2250         * @see railo.runtime.PageContext#getPsq()
2251         */
2252        public boolean getPsq() {
2253                    return psq;
2254            }
2255            
2256        /**
2257         * @see railo.runtime.PageContext#setLocale(java.util.Locale)
2258         */
2259        public void setLocale(Locale locale) {
2260                    
2261                    //String old=GetLocale.call(pc);
2262                    this.locale=locale;
2263            HttpServletResponse rsp = getHttpServletResponse();
2264            
2265            String charEnc = rsp.getCharacterEncoding();
2266            rsp.setLocale(locale);
2267            if(charEnc.equalsIgnoreCase("UTF-8")) {
2268                    rsp.setContentType("text/html; charset=UTF-8");
2269            }
2270            else if(!charEnc.equalsIgnoreCase(rsp.getCharacterEncoding())) {
2271                    rsp.setContentType("text/html; charset=" + charEnc);
2272            }
2273            }
2274        
2275    
2276        /**
2277         * @see railo.runtime.PageContext#setLocale(java.lang.String)
2278         */
2279        public void setLocale(String strLocale) throws ExpressionException {
2280                    setLocale(Caster.toLocale(strLocale));
2281            }
2282    
2283        /**
2284         * @see railo.runtime.PageContext#setErrorPage(railo.runtime.err.ErrorPage)
2285         */
2286        public void setErrorPage(ErrorPage ep) {
2287                    errorPagePool.setErrorPage(ep);
2288            }
2289            
2290        /**
2291         * @see railo.runtime.PageContext#use(java.lang.Class)
2292         * /
2293        public Tag use(Class tagClass) throws PageException {
2294            
2295            parentTag=currentTag;
2296                    currentTag= tagHandlerPool.use(tagClass);
2297            if(currentTag==parentTag) throw new ApplicationException("");
2298            currentTag.setPageContext(this);
2299            currentTag.setParent(parentTag);
2300            return currentTag;
2301            }*/
2302    
2303        /**
2304         *
2305         * @see railo.runtime.PageContext#use(java.lang.String)
2306         */
2307        public Tag use(String tagClassName) throws PageException {
2308    
2309            parentTag=currentTag;
2310                    currentTag= tagHandlerPool.use(tagClassName);
2311            if(currentTag==parentTag) throw new ApplicationException("");
2312            currentTag.setPageContext(this);
2313            currentTag.setParent(parentTag);
2314            return currentTag;
2315            }
2316        
2317        /**
2318         * @see railo.runtime.PageContext#use(java.lang.Class)
2319         */
2320        public Tag use(Class clazz) throws PageException {
2321            return use(clazz.getName());
2322            }
2323            
2324        /**
2325         * @see railo.runtime.PageContext#reuse(javax.servlet.jsp.tagext.Tag)
2326         */
2327        public void reuse(Tag tag) throws PageException {
2328            currentTag=tag.getParent();
2329            tagHandlerPool.reuse(tag);
2330            }
2331    
2332        /**
2333         * @see railo.runtime.PageContext#getQueryCache()
2334         */
2335        public QueryCache getQueryCache() {
2336            return queryCache;
2337        }
2338        
2339        /**
2340         * @see railo.runtime.PageContext#initBody(javax.servlet.jsp.tagext.BodyTag, int)
2341         */
2342        public void initBody(BodyTag bodyTag, int state) throws JspException {
2343            if (state != Tag.EVAL_BODY_INCLUDE) {
2344                bodyTag.setBodyContent(pushBody());
2345                bodyTag.doInitBody();
2346            }
2347        }
2348        
2349        /**
2350         * @see railo.runtime.PageContext#releaseBody(javax.servlet.jsp.tagext.BodyTag, int)
2351         */
2352        public void releaseBody(BodyTag bodyTag, int state) {
2353            if(bodyTag instanceof TryCatchFinally) {
2354                ((TryCatchFinally)bodyTag).doFinally();
2355            }
2356            if (state != Tag.EVAL_BODY_INCLUDE)popBody();
2357        }
2358        
2359        /* *
2360         * @return returns the cfml compiler 
2361         * /
2362        public CFMLCompiler getCompiler() {
2363            return compiler;
2364        }*/
2365        
2366        /**
2367         * @see railo.runtime.PageContext#setVariablesScope(railo.runtime.type.Scope)
2368         */
2369        public void setVariablesScope(Variables variables) {
2370            this.variables=variables;
2371            undefinedScope().setVariableScope(variables);
2372            
2373            if(variables instanceof ComponentScope) {
2374                    activeComponent=((ComponentScope)variables).getComponent();
2375                /*if(activeComponent.getAbsName().equals("jm.pixeltex.supersuperApp")){
2376                    print.dumpStack();
2377                }*/
2378            }
2379            else {
2380                activeComponent=null;
2381            }
2382        }
2383    
2384        
2385    
2386        /**
2387         * @see railo.runtime.PageContext#getActiveComponent()
2388         */
2389        public Component getActiveComponent() {
2390            return activeComponent;
2391        }
2392        
2393        
2394        
2395        
2396        /**
2397         * @see railo.runtime.PageContext#getRemoteUser()
2398         */
2399        public Credential getRemoteUser() throws PageException {
2400            if(remoteUser==null) {
2401                    String name=Login.getApplicationName(applicationContext);
2402                        Resource roles = config.getConfigDir().getRealResource("roles");
2403                        
2404                    if(applicationContext.getLoginStorage()==Scope.SCOPE_SESSION) {
2405                    Object auth = sessionScope().get(name,null);
2406                    if(auth!=null) {
2407                        remoteUser=CredentialImpl.decode(auth,roles);
2408                    }
2409                }
2410                else if(applicationContext.getLoginStorage()==Scope.SCOPE_COOKIE) {
2411                    Object auth = cookieScope().get(name,null);
2412                    if(auth!=null) {
2413                        remoteUser=CredentialImpl.decode(auth,roles);
2414                    }
2415                }
2416            }
2417            return remoteUser;
2418        }
2419        
2420        /**
2421         * @see railo.runtime.PageContext#clearRemoteUser()
2422         */
2423        public void clearRemoteUser() {
2424            if(remoteUser!=null)remoteUser=null;
2425            String name=Login.getApplicationName(applicationContext);
2426                
2427            cookieScope().removeEL(KeyImpl.init(name));
2428            try {
2429                            sessionScope().removeEL(KeyImpl.init(name));
2430                    } catch (PageException e) {}
2431            
2432        }
2433        
2434        /**
2435         * @see railo.runtime.PageContext#setRemoteUser(railo.runtime.security.Credential)
2436         */
2437        public void setRemoteUser(Credential remoteUser) {
2438            this.remoteUser = remoteUser;
2439        }
2440        
2441        /**
2442         * @see railo.runtime.PageContext#getVariableUtil()
2443         */
2444        public VariableUtil getVariableUtil() {
2445            return variableUtil;
2446        }
2447    
2448        /**
2449         * @see railo.runtime.PageContext#throwCatch()
2450         */
2451        public void throwCatch() throws PageException {
2452            if(exception!=null) throw exception;
2453            else throw new ApplicationException("invalid context for tag/script expression rethow");
2454        }
2455    
2456        /**
2457         * @see railo.runtime.PageContext#setCatch(java.lang.Throwable)
2458         */
2459        public PageException setCatch(Throwable t) {
2460            if(t==null) {
2461                    exception=null;
2462                    undefinedScope().removeEL(CFCATCH);
2463            }
2464            else {
2465                    exception = Caster.toPageException(t);
2466                    undefinedScope().setEL(CFCATCH,exception.getCatchBlock(this));
2467                    if(config.debug()) ((DebuggerImpl)debugger).addException(config,exception);
2468            }
2469            return exception;
2470        }
2471        
2472        public void setCatch(PageException pe) {
2473            exception = pe;
2474            if(pe==null) {
2475                    undefinedScope().removeEL(CFCATCH);
2476            }
2477            else {
2478                    undefinedScope().setEL(CFCATCH,pe.getCatchBlock(this));
2479                    if(config.debug()) ((DebuggerImpl)debugger).addException(config,exception);
2480            }
2481        }
2482        
2483        public void setCatch(PageException pe,boolean caught, boolean store) {
2484                    //print.err("fdEnabled:"+fdEnabled+"; caught:"+caught+"; type:"+pe.getTypeAsString()+"; message:"+pe.getMessage()+";");
2485            if(fdEnabled){
2486                    FDSignal.signal(pe, caught);
2487            }
2488            exception = pe;
2489            if(store){
2490                    if(pe==null) {
2491                            undefinedScope().removeEL(CFCATCH);
2492                    }
2493                    else {
2494                            undefinedScope().setEL(CFCATCH,pe.getCatchBlock(this));
2495                            if(config.debug()) ((DebuggerImpl)debugger).addException(config,exception);
2496                    }
2497            }
2498        }
2499        
2500        /**
2501         * @return return current catch
2502         */
2503        public PageException getCatch() {
2504            return exception;
2505        }
2506        
2507        /**
2508         * @see railo.runtime.PageContext#clearCatch()
2509         */
2510        public void clearCatch() {
2511            exception = null;
2512            undefinedScope().removeEL(CFCATCH);
2513        }
2514    
2515        /**
2516         * @see railo.runtime.PageContext#addPageSource(railo.runtime.PageSource, boolean)
2517         */
2518        public void addPageSource(PageSource ps, boolean alsoInclude) {
2519            pathList.add(ps);
2520            if(alsoInclude) 
2521                includePathList.add(ps);
2522        }
2523        
2524    
2525        public void addPageSource(PageSource ps, PageSource psInc) {
2526            pathList.add(ps);
2527            if(psInc!=null) 
2528                includePathList.add(psInc);
2529        }
2530    
2531        /**
2532         * @see railo.runtime.PageContext#removeLastPageSource(boolean)
2533         */
2534        public void removeLastPageSource(boolean alsoInclude) {
2535            pathList.removeLast();
2536            if(alsoInclude) 
2537                includePathList.removeLast();
2538        }
2539    
2540        /**
2541         * @see railo.runtime.PageContext#getFTPPool()
2542         */
2543        public FTPPool getFTPPool() {
2544            return ftpPool;
2545        }
2546    
2547        /* *
2548         * @return Returns the manager.
2549         * /
2550        public DataSourceManager getManager() {
2551            return manager;
2552        }*/
2553        
2554        /**
2555         * @see railo.runtime.PageContext#getApplicationContext()
2556         */
2557        public ApplicationContext getApplicationContext() {
2558            return applicationContext;
2559        }
2560        
2561        /**
2562         * @see railo.runtime.PageContext#setApplicationContext(railo.runtime.util.ApplicationContext)
2563         */
2564        public void setApplicationContext(ApplicationContext applicationContext) {
2565            
2566            session=null;
2567            application=null;
2568            client=null;
2569            this.applicationContext = (ApplicationContextPro) applicationContext;
2570            
2571            int scriptProtect = applicationContext.getScriptProtect();
2572            
2573            // ScriptProtecting
2574            if(config.mergeFormAndURL()) {
2575                    form.setScriptProtecting(
2576                                    (scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0 
2577                                    || 
2578                                    (scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0);
2579            }
2580            else {
2581                form.setScriptProtecting((scriptProtect&ApplicationContext.SCRIPT_PROTECT_FORM)>0);
2582                url.setScriptProtecting((scriptProtect&ApplicationContext.SCRIPT_PROTECT_URL)>0);
2583            }
2584            cookie.setScriptProtecting((scriptProtect&ApplicationContext.SCRIPT_PROTECT_COOKIE)>0);
2585            cgi.setScriptProtecting((scriptProtect&ApplicationContext.SCRIPT_PROTECT_CGI)>0);
2586            undefined.reinitialize(this);
2587        }
2588        
2589        /**
2590         * @return return  value of method "onApplicationStart" or true
2591         * @throws PageException 
2592         */
2593        public boolean initApplicationContext() throws PageException {
2594            boolean initSession=false;
2595                AppListenerSupport listener = (AppListenerSupport) config.getApplicationListener();
2596            KeyLock<String> lock = config.getContextLock();
2597            String name=StringUtil.emptyIfNull(applicationContext.getName());
2598            String token=name+":"+getCFID();
2599            
2600            Lock tokenLock = lock.lock(token,getRequestTimeout());
2601            //print.o("outer-lock  :"+token);
2602            try {
2603                    // check session before executing any code
2604                    initSession=applicationContext.isSetSessionManagement() && listener.hasOnSessionStart(this) && !scopeContext.hasExistingSessionScope(this);
2605                    
2606                    // init application
2607                    
2608                    Lock nameLock = lock.lock(name,getRequestTimeout());
2609                    //print.o("inner-lock  :"+token);
2610                    try {
2611                            RefBoolean isNew=new RefBooleanImpl(false);
2612                                application=scopeContext.getApplicationScope(this,isNew);// this is needed that the application scope is initilized
2613                            if(isNew.toBooleanValue()) {
2614                                        try {
2615                                                    if(!listener.onApplicationStart(this)) {
2616                                                            scopeContext.removeApplicationScope(this);
2617                                                        return false;
2618                                                    }
2619                                            } catch (PageException pe) {
2620                                                    scopeContext.removeApplicationScope(this);
2621                                                    throw pe;
2622                                            }
2623                                }
2624                    }
2625                    finally{
2626                            //print.o("inner-unlock:"+token);
2627                            lock.unlock(nameLock);
2628                    }
2629            
2630                    // init session
2631                        if(initSession) {
2632                            scopeContext.getSessionScope(this, DUMMY_BOOL);// this is needed that the session scope is initilized
2633                            listener.onSessionStart(this);
2634                            }
2635            }
2636            finally{
2637                    //print.o("outer-unlock:"+token);
2638                    lock.unlock(tokenLock);
2639            }
2640                return true;
2641        }
2642        
2643    
2644        /**
2645         * @return the scope factory
2646         */
2647        public ScopeFactory getScopeFactory() {
2648            return scopeFactory;
2649        }
2650    
2651        
2652        
2653        
2654        /**
2655         * @see railo.runtime.PageContext#getCurrentTag()
2656         */
2657        public Tag getCurrentTag() {
2658            return currentTag;
2659        }
2660    
2661        /**
2662         * @see railo.runtime.PageContext#getStartTime()
2663         */
2664        public long getStartTime() {
2665            return startTime;
2666        }
2667        
2668        /**
2669         * @see railo.runtime.PageContext#getThread()
2670         */
2671        public Thread getThread() {
2672            return thread;
2673        }
2674        
2675    
2676    
2677            public void setThread(Thread thread) {
2678                    this.thread=thread;
2679            }
2680    
2681        /**
2682         * @see railo.runtime.PageContext#getExecutionTime()
2683         */
2684        public int getExecutionTime() {
2685            return executionTime;
2686        }
2687    
2688        /**
2689         * @see railo.runtime.PageContext#setExecutionTime(int)
2690         */
2691        public void setExecutionTime(int executionTime) {
2692            this.executionTime = executionTime;
2693        }
2694    
2695        /**
2696         * @see railo.runtime.PageContext#compile(railo.runtime.PageSource)
2697         */
2698        public synchronized void compile(PageSource pageSource) throws PageException {
2699            Resource classRootDir = pageSource.getMapping().getClassRootDirectory();
2700            
2701            try {
2702                config.getCompiler().compile(
2703                        config,
2704                        pageSource,
2705                        config.getTLDs(),
2706                        config.getFLDs(),
2707                        classRootDir,
2708                        pageSource.getJavaName()
2709                        );
2710            } catch (Exception e) {
2711                throw Caster.toPageException(e);
2712            }        
2713        }
2714    
2715        /**
2716         * @see railo.runtime.PageContext#compile(java.lang.String)
2717         */
2718        public void compile(String realPath) throws PageException {
2719            SystemOut.printDate("method PageContext.compile(String) should no longer be used!");
2720            compile(PageSourceImpl.best(getRelativePageSources(realPath)));
2721        }
2722        
2723        public HttpServlet getServlet() {
2724            return servlet;
2725        }
2726    
2727        /**
2728         * @see railo.runtime.PageContext#loadComponent(java.lang.String)
2729         */
2730        public railo.runtime.Component loadComponent(String compPath) throws PageException {
2731            return ComponentLoader.loadComponent(this,compPath,null,null);
2732        }
2733    
2734            /**
2735             * @return the base
2736             */
2737            public PageSource getBase() {
2738                    return base;
2739            }
2740    
2741            /**
2742             * @param base the base to set
2743             */
2744            public void setBase(PageSource base) {
2745                    this.base = base;
2746            }
2747    
2748            /**
2749             * @return the isCFCRequest
2750             */
2751            public boolean isCFCRequest() {
2752                    return isCFCRequest;
2753            }
2754            
2755            /**
2756             * @see railo.runtime.config.Config#getDataSourceManager()
2757             */
2758            public DataSourceManager getDataSourceManager() {
2759                    return manager;
2760            }
2761    
2762            public Object evaluate(String expression) throws PageException {
2763                    // TODO kann das objekt nicht variable von object sein
2764                    return new CFMLExpressionInterpreter().interpret(this,expression);
2765            }
2766    
2767            /**
2768             * @return the activeUDF
2769             */
2770            public UDF getActiveUDF() {
2771                    return activeUDF;
2772            }
2773    
2774            /**
2775             * @param activeUDF the activeUDF to set
2776             */
2777            public void setActiveUDF(UDF activeUDF) {
2778                    this.activeUDF = activeUDF;
2779            }
2780    
2781            /**
2782             *
2783             * @see railo.runtime.PageContext#getCFMLFactory()
2784             */
2785            public CFMLFactory getCFMLFactory() {
2786                    return config.getFactory();
2787            }
2788    
2789            /**
2790             * @see railo.runtime.PageContext#getParentPageContext()
2791             */
2792            public PageContext getParentPageContext() {
2793                    return parent;
2794            }
2795    
2796    
2797            /**
2798             * @see railo.runtime.PageContext#getThreadScopeNames()
2799             */
2800            public String[] getThreadScopeNames() {
2801                    if(threads==null)return new String[0];
2802                    Set ks = threads.keySet();
2803                    return (String[]) ks.toArray(new String[ks.size()]);
2804            }
2805            
2806            /**
2807             * @see railo.runtime.PageContext#getThreadScope(java.lang.String)
2808             */
2809            public Threads getThreadScope(String name) {
2810                    if(threads==null)threads=new StructImpl();
2811                    Object obj = threads.get(name,null);
2812                    if(obj instanceof Threads)return (Threads) obj;
2813                    return null;
2814            }
2815            
2816            public Object getThreadScope(Collection.Key name,Object defaultValue) {
2817                    if(threads==null)threads=new StructImpl();
2818                    if(name.equalsIgnoreCase(CFTHREAD)) return threads;
2819                    return threads.get(name,defaultValue);
2820            }
2821            
2822            public Object getThreadScope(String name,Object defaultValue) {
2823                    if(threads==null)threads=new StructImpl();
2824                    if(name.equalsIgnoreCase(CFTHREAD.getLowerString())) return threads;
2825                    return threads.get(name,defaultValue);
2826            }
2827    
2828            /**
2829             * @see railo.runtime.PageContext#setThreadScope(java.lang.String, railo.runtime.type.scope.Threads)
2830             */
2831            public void setThreadScope(String name,Threads ct) {
2832                    hasFamily=true;
2833                    if(threads==null)       threads=new StructImpl();
2834                    threads.setEL(name, ct);
2835            }
2836            
2837            public void setThreadScope(Collection.Key name,Threads ct) {
2838                    hasFamily=true;
2839                    if(threads==null)       threads=new StructImpl();
2840                    threads.setEL(name, ct);
2841            }
2842    
2843            /**
2844             * @see railo.runtime.PageContext#hasFamily()
2845             */
2846            public boolean hasFamily() {
2847                    return hasFamily;
2848            }
2849            
2850    
2851            public DatasourceConnection _getConnection(String datasource, String user,String pass) throws PageException {
2852                    return _getConnection(config.getDataSource(datasource),user,pass);
2853            }
2854            
2855            public DatasourceConnection _getConnection(DataSource ds, String user,String pass) throws PageException {
2856                    
2857                    String id=DatasourceConnectionPool.createId(ds,user,pass);
2858                    DatasourceConnection dc=(DatasourceConnection) conns.get(id);
2859                    if(dc!=null && DatasourceConnectionPool.isValid(dc,null)){
2860                            return dc;
2861                    }
2862                    dc=config.getDatasourceConnectionPool().getDatasourceConnection(this,ds, user, pass);
2863                    conns.put(id, dc);
2864                    return dc;
2865            }
2866    
2867            /**
2868             * @see railo.runtime.PageContext#getTimeZone()
2869             */
2870            public TimeZone getTimeZone() {
2871                    if(timeZone==null) timeZone=config.getTimeZone();
2872                    return timeZone;
2873            }
2874            /**
2875             * @see railo.runtime.PageContext#setTimeZone(java.util.TimeZone)
2876             */
2877            public void  setTimeZone(TimeZone timeZone) {
2878                    this.timeZone=timeZone;
2879            }
2880    
2881    
2882            /**
2883             * @return the requestId
2884             */
2885            public int getRequestId() {
2886                    return requestId;
2887            }
2888    
2889            private Set<String> pagesUsed=new HashSet<String>();
2890            
2891            
2892    
2893    
2894    
2895            public boolean isTrusted(Page page) {
2896                    if(page==null)return false;
2897                    short it = config.getInspectTemplate();
2898                    if(it==ConfigImpl.INSPECT_NEVER)return true;
2899                    if(it==ConfigImpl.INSPECT_ALWAYS)return false;
2900                    
2901                    return pagesUsed.contains(""+page.hashCode());
2902            }
2903            
2904            public void setPageUsed(Page page) {
2905                    pagesUsed.add(""+page.hashCode());
2906            }
2907    
2908            /**
2909             * @param line
2910             * @deprecated no longer supported and ignored
2911             */
2912            public void exeLogEndline(int line){
2913                    //execLog.line(line);
2914            }
2915            public void exeLogStart(int line,String id){
2916                    if(execLog!=null)execLog.start(line, id);
2917            }
2918            public void exeLogEnd(int line,String id){
2919                    if(execLog!=null)execLog.end(line, id);
2920            }
2921    
2922            
2923            /**
2924             * @param create if set to true, railo creates a session when not exist
2925             * @return
2926             * @throws PageException
2927             */
2928            public ORMSession getORMSession(boolean create) throws PageException {
2929                    if(ormSession==null || !ormSession.isValid())   {
2930                            if(!create) return null;
2931                            ormSession=config.getORMEngine(this).createSession(this);
2932                    }
2933                    DatasourceManagerImpl manager = (DatasourceManagerImpl) getDataSourceManager();
2934                    manager.add(this,ormSession);
2935                    
2936                    return ormSession;
2937                    
2938                    
2939            }
2940    
2941            public void resetSession() {
2942                    this.session=null;
2943            }
2944            /**
2945             * @return the gatewayContext
2946             */
2947            public boolean isGatewayContext() {
2948                    return gatewayContext;
2949            }
2950    
2951    
2952    
2953            /**
2954             * @param gatewayContext the gatewayContext to set
2955             */
2956            public void setGatewayContext(boolean gatewayContext) {
2957                    this.gatewayContext = gatewayContext;
2958            }
2959    
2960    
2961    
2962            public void setServerPassword(String serverPassword) {
2963                    this.serverPassword=serverPassword;
2964            }
2965            public String getServerPassword() {
2966                    return serverPassword;
2967            }
2968    
2969            public short getSessionType() {
2970                    if(isGatewayContext())return Config.SESSION_TYPE_CFML;
2971                    return applicationContext.getSessionType();
2972            }
2973            
2974            // this is just a wrapper method for ACF
2975            public Scope SymTab_findBuiltinScope(String name) throws PageException {
2976                    return scope(name, null);
2977            }
2978    }