001    // Copyright 2004, 2005 The Apache Software Foundation
002    //
003    // Licensed under the Apache License, Version 2.0 (the "License");
004    // you may not use this file except in compliance with the License.
005    // You may obtain a copy of the License at
006    //
007    //     http://www.apache.org/licenses/LICENSE-2.0
008    //
009    // Unless required by applicable law or agreed to in writing, software
010    // distributed under the License is distributed on an "AS IS" BASIS,
011    // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
012    // See the License for the specific language governing permissions and
013    // limitations under the License.
014    
015    package org.apache.tapestry.engine;
016    
017    import java.io.IOException;
018    import java.util.ArrayList;
019    import java.util.List;
020    import java.util.Locale;
021    
022    import org.apache.commons.logging.Log;
023    import org.apache.commons.logging.LogFactory;
024    import org.apache.hivemind.ApplicationRuntimeException;
025    import org.apache.hivemind.ClassResolver;
026    import org.apache.hivemind.util.Defense;
027    import org.apache.hivemind.util.ToStringBuilder;
028    import org.apache.tapestry.Constants;
029    import org.apache.tapestry.IEngine;
030    import org.apache.tapestry.IPage;
031    import org.apache.tapestry.IRequestCycle;
032    import org.apache.tapestry.PageRedirectException;
033    import org.apache.tapestry.RedirectException;
034    import org.apache.tapestry.StaleLinkException;
035    import org.apache.tapestry.StaleSessionException;
036    import org.apache.tapestry.listener.ListenerMap;
037    import org.apache.tapestry.services.DataSqueezer;
038    import org.apache.tapestry.services.Infrastructure;
039    import org.apache.tapestry.spec.IApplicationSpecification;
040    import org.apache.tapestry.web.WebRequest;
041    import org.apache.tapestry.web.WebResponse;
042    
043    /**
044     * Basis for building real Tapestry applications. Immediate subclasses provide different strategies
045     * for managing page state and other resources between request cycles.
046     * <p>
047     * Note: much of this description is <em>in transition</em> as part of Tapestry 4.0. All ad-hoc
048     * singletons and such are being replaced with HiveMind services.
049     * <p>
050     * Uses a shared instance of {@link ITemplateSource},{@link ISpecificationSource},
051     * {@link IScriptSource}and {@link IComponentMessagesSource}stored as attributes of the
052     * {@link ServletContext}(they will be shared by all sessions).
053     * <p>
054     * An engine is designed to be very lightweight. Particularily, it should <b>never </b> hold
055     * references to any {@link IPage}or {@link org.apache.tapestry.IComponent}objects. The entire
056     * system is based upon being able to quickly rebuild the state of any page(s).
057     * <p>
058     * Where possible, instance variables should be transient. They can be restored inside
059     * {@link #setupForRequest(RequestContext)}.
060     * <p>
061     * In practice, a subclass (usually {@link BaseEngine}) is used without subclassing. Instead, a
062     * visit object is specified. To facilitate this, the application specification may include a
063     * property, <code>org.apache.tapestry.visit-class</code> which is the class name to instantiate
064     * when a visit object is first needed. See {@link #createVisit(IRequestCycle)}for more details.
065     * <p>
066     * Some of the classes' behavior is controlled by JVM system properties (typically only used during
067     * development): <table border=1>
068     * <tr>
069     * <th>Property</th>
070     * <th>Description</th>
071     * </tr>
072     * <tr>
073     * <td>org.apache.tapestry.enable-reset-service</td>
074     * <td>If true, enabled an additional service, reset, that allow page, specification and template
075     * caches to be cleared on demand. See {@link #isResetServiceEnabled()}.</td>
076     * </tr>
077     * <tr>
078     * <td>org.apache.tapestry.disable-caching</td>
079     * <td>If true, then the page, specification, template and script caches will be cleared after each
080     * request. This slows things down, but ensures that the latest versions of such files are used.
081     * Care should be taken that the source directories for the files preceeds any versions of the files
082     * available in JARs or WARs.</td>
083     * </tr>
084     * </table>
085     * 
086     * @author Howard Lewis Ship
087     */
088    
089    public abstract class AbstractEngine implements IEngine
090    {
091        /**
092         * The name of the application specification property used to specify the class of the visit
093         * object.
094         */
095    
096        public static final String VISIT_CLASS_PROPERTY_NAME = "org.apache.tapestry.visit-class";
097        
098        private static final Log LOG = LogFactory.getLog(AbstractEngine.class);
099    
100        /**
101         * The link to the world of HiveMind services.
102         * 
103         * @since 4.0
104         */
105        private Infrastructure _infrastructure;
106    
107        private ListenerMap _listeners;
108    
109        /**
110         * The curent locale for the engine, which may be changed at any time.
111         */
112    
113        private Locale _locale;
114    
115        /**
116         * @see org.apache.tapestry.error.ExceptionPresenter
117         */
118    
119        protected void activateExceptionPage(IRequestCycle cycle, Throwable cause)
120        {
121            _infrastructure.getExceptionPresenter().presentException(cycle, cause);
122        }
123    
124        /**
125         * Writes a detailed report of the exception to <code>System.err</code>.
126         * 
127         * @see org.apache.tapestry.error.RequestExceptionReporter
128         */
129    
130        public void reportException(String reportTitle, Throwable ex)
131        {
132            _infrastructure.getRequestExceptionReporter().reportRequestException(reportTitle, ex);
133        }
134    
135        /**
136         * Invoked at the end of the request cycle to release any resources specific to the request
137         * cycle. This implementation does nothing and may be overriden freely.
138         */
139    
140        protected void cleanupAfterRequest(IRequestCycle cycle)
141        {
142    
143        }
144    
145        /**
146         * Returns the locale for the engine. This is initially set by the {@link ApplicationServlet}
147         * but may be updated by the application.
148         */
149    
150        public Locale getLocale()
151        {
152            return _locale;
153        }
154    
155        /**
156         * Returns a service with the given name.
157         * 
158         * @see Infrastructure#getServiceMap()
159         * @see org.apache.tapestry.services.ServiceMap
160         */
161    
162        public IEngineService getService(String name)
163        {
164            return _infrastructure.getServiceMap().getService(name);
165        }
166    
167        /** @see Infrastructure#getApplicationSpecification() */
168    
169        public IApplicationSpecification getSpecification()
170        {
171            return _infrastructure.getApplicationSpecification();
172        }
173    
174        /** @see Infrastructure#getSpecificationSource() */
175    
176        public ISpecificationSource getSpecificationSource()
177        {
178            return _infrastructure.getSpecificationSource();
179        }
180    
181        /**
182         * Invoked, typically, when an exception occurs while servicing the request. This method resets
183         * the output, sets the new page and renders it.
184         */
185    
186        protected void redirect(String pageName, IRequestCycle cycle,
187                ApplicationRuntimeException exception) throws IOException
188        {
189            IPage page = cycle.getPage(pageName);
190    
191            cycle.activate(page);
192    
193            renderResponse(cycle);
194        }
195    
196        /**
197         * Delegates to
198         * {@link org.apache.tapestry.services.ResponseRenderer#renderResponse(IRequestCycle)}.
199         */
200    
201        public void renderResponse(IRequestCycle cycle) throws IOException
202        {
203            _infrastructure.getResponseRenderer().renderResponse(cycle);
204        }
205    
206        /**
207         * Delegate method for the servlet. Services the request.
208         */
209    
210        public void service(WebRequest request, WebResponse response) throws IOException
211        {
212            IRequestCycle cycle = null;
213            IEngineService service = null;
214    
215            if (_infrastructure == null)
216                _infrastructure = (Infrastructure) request.getAttribute(Constants.INFRASTRUCTURE_KEY);
217    
218            // Create the request cycle; if this fails, there's not much that can be done ... everything
219            // else in Tapestry relies on the RequestCycle.
220    
221            try
222            {
223                cycle = _infrastructure.getRequestCycleFactory().newRequestCycle(this);
224            }
225            catch (RuntimeException ex)
226            {
227                throw ex;
228            }
229            catch (Exception ex)
230            {
231                throw new IOException(ex.getMessage());
232            }
233    
234            try
235            {
236                try
237                {
238                    service = cycle.getService();
239                    // Let the service handle the rest of the request.
240                    
241                    service.service(cycle);
242                    
243                    return;
244                }
245                catch (PageRedirectException ex)
246                {
247                    handlePageRedirectException(cycle, ex);
248                }
249                catch (RedirectException ex)
250                {
251                    handleRedirectException(cycle, ex);
252                }
253                catch (StaleLinkException ex)
254                {
255                    handleStaleLinkException(cycle, ex);
256                }
257                catch (StaleSessionException ex)
258                {
259                    handleStaleSessionException(cycle, ex);
260                }
261            }
262            catch (Exception ex)
263            {
264                // Attempt to switch to the exception page. However, this may itself
265                // fail for a number of reasons, in which case an ApplicationRuntimeException is
266                // thrown.
267    
268                if (LOG.isDebugEnabled())
269                    LOG.debug("Uncaught exception", ex);
270    
271                activateExceptionPage(cycle, ex);
272            }
273            finally
274            {
275                try
276                {
277                    cycle.cleanup();
278                    _infrastructure.getApplicationStateManager().flush();
279                }
280                catch (Exception ex)
281                {
282                    reportException(EngineMessages.exceptionDuringCleanup(ex), ex);
283                }
284            }
285        }
286    
287        /**
288         * Handles {@link PageRedirectException} which involves executing
289         * {@link IRequestCycle#activate(IPage)} on the target page (of the exception), until either a
290         * loop is found, or a page succesfully activates.
291         * <p>
292         * This should generally not be overriden in subclasses.
293         * 
294         * @since 3.0
295         */
296    
297        protected void handlePageRedirectException(IRequestCycle cycle, PageRedirectException exception)
298                throws IOException
299        {
300            List pageNames = new ArrayList();
301    
302            String pageName = exception.getTargetPageName();
303    
304            while (true)
305            {
306                if (pageNames.contains(pageName))
307                {
308                    pageNames.add(pageName);
309    
310                    throw new ApplicationRuntimeException(EngineMessages.validateCycle(pageNames));
311                }
312    
313                // Record that this page has been a target.
314    
315                pageNames.add(pageName);
316    
317                try
318                {
319                    // Attempt to activate the new page.
320    
321                    cycle.activate(pageName);
322    
323                    break;
324                }
325                catch (PageRedirectException secondRedirectException)
326                {
327                    pageName = secondRedirectException.getTargetPageName();
328                }
329            }
330    
331            renderResponse(cycle);
332        }
333    
334        /**
335         * Invoked by {@link #service(WebRequest, WebResponse)} if a {@link StaleLinkException} is
336         * thrown by the {@link IEngineService service}. This implementation sets the message property
337         * of the StaleLink page to the message provided in the exception, then invokes
338         * {@link #redirect(String, IRequestCycle, ApplicationRuntimeException)} to render the StaleLink
339         * page.
340         * <p>
341         * Subclasses may overide this method (without invoking this implementation). A better practice
342         * is to contribute an alternative implementation of
343         * {@link org.apache.tapestry.error.StaleLinkExceptionPresenter} to the
344         * tapestry.InfrastructureOverrides configuration point.
345         * <p>
346         * A common practice is to present an error message on the application's Home page. Alternately,
347         * the application may provide its own version of the StaleLink page, overriding the framework's
348         * implementation (probably a good idea, because the default page hints at "application errors"
349         * and isn't localized). The overriding StaleLink implementation must implement a message
350         * property of type String.
351         * 
352         * @since 0.2.10
353         */
354    
355        protected void handleStaleLinkException(IRequestCycle cycle, StaleLinkException exception)
356                throws IOException
357        {
358            _infrastructure.getStaleLinkExceptionPresenter()
359                    .presentStaleLinkException(cycle, exception);
360        }
361    
362        /**
363         * Invoked by {@link #service(WebRequest, WebResponse)} if a {@link StaleSessionException} is
364         * thrown by the {@link IEngineService service}. This implementation uses the
365         * {@link org.apache.tapestry.error.StaleSessionExceptionPresenter} to render the StaleSession
366         * page.
367         * <p>
368         * Subclasses may overide this method (without invoking this implementation), but it is better
369         * to override the tapestry.error.StaleSessionExceptionReporter service instead (or contribute a
370         * replacement to the tapestry.InfrastructureOverrides configuration point).
371         * 
372         * @since 0.2.10
373         */
374    
375        protected void handleStaleSessionException(IRequestCycle cycle, StaleSessionException exception)
376                throws IOException
377        {
378            _infrastructure.getStaleSessionExceptionPresenter().presentStaleSessionException(
379                    cycle,
380                    exception);
381        }
382    
383        /**
384         * Changes the locale for the engine.
385         */
386    
387        public void setLocale(Locale value)
388        {
389            Defense.notNull(value, "locale");
390    
391            _locale = value;
392    
393            // The locale may be set before the engine is initialized with the Infrastructure.
394    
395            if (_infrastructure != null)
396                _infrastructure.setLocale(value);
397        }
398    
399        /**
400         * @see Infrastructure#getClassResolver()
401         */
402    
403        public ClassResolver getClassResolver()
404        {
405            return _infrastructure.getClassResolver();
406        }
407    
408        /**
409         * Generates a description of the instance. Invokes {@link #extendDescription(ToStringBuilder)}
410         * to fill in details about the instance.
411         * 
412         * @see #extendDescription(ToStringBuilder)
413         */
414    
415        public String toString()
416        {
417            ToStringBuilder builder = new ToStringBuilder(this);
418    
419            builder.append("locale", _locale);
420    
421            return builder.toString();
422        }
423    
424        /**
425         * Gets the visit object from the
426         * {@link org.apache.tapestry.engine.state.ApplicationStateManager}, creating it if it does not
427         * already exist.
428         * <p>
429         * As of Tapestry 4.0, this will always create the visit object, possibly creating a new session
430         * in the process.
431         */
432    
433        public Object getVisit()
434        {
435            return _infrastructure.getApplicationStateManager().get("visit");
436        }
437    
438        public void setVisit(Object visit)
439        {
440            _infrastructure.getApplicationStateManager().store("visit", visit);
441        }
442    
443        /**
444         * Gets the visit object from the
445         * {@link org.apache.tapestry.engine.state.ApplicationStateManager}, which will create it as
446         * necessary.
447         */
448    
449        public Object getVisit(IRequestCycle cycle)
450        {
451            return getVisit();
452        }
453    
454        public boolean getHasVisit()
455        {
456            return _infrastructure.getApplicationStateManager().exists("visit");
457        }
458    
459        /**
460         * Returns the global object for the application. The global object is created at the start of
461         * the request ({@link #setupForRequest(RequestContext)}invokes
462         * {@link #createGlobal(RequestContext)}if needed), and is stored into the
463         * {@link ServletContext}. All instances of the engine for the application share the global
464         * object; however, the global object is explicitly <em>not</em> replicated to other servers
465         * within a cluster.
466         * 
467         * @since 2.3
468         */
469    
470        public Object getGlobal()
471        {
472            return _infrastructure.getApplicationStateManager().get("global");
473        }
474    
475        public IScriptSource getScriptSource()
476        {
477            return _infrastructure.getScriptSource();
478        }
479    
480        /**
481         * Allows subclasses to include listener methods easily.
482         * 
483         * @since 1.0.2
484         */
485    
486        public ListenerMap getListeners()
487        {
488            if (_listeners == null)
489                _listeners = _infrastructure.getListenerMapSource().getListenerMapForObject(this);
490    
491            return _listeners;
492        }
493    
494        /**
495         * Invoked when a {@link RedirectException} is thrown during the processing of a request.
496         * 
497         * @throws ApplicationRuntimeException
498         *             if an {@link IOException},{@link ServletException}is thrown by the redirect,
499         *             or if no {@link RequestDispatcher}can be found for local resource.
500         * @since 2.2
501         */
502    
503        protected void handleRedirectException(IRequestCycle cycle, RedirectException redirectException)
504        {
505            String location = redirectException.getRedirectLocation();
506    
507            if (LOG.isDebugEnabled())
508                LOG.debug("Redirecting to: " + location);
509    
510            _infrastructure.getRequest().forward(location);
511        }
512    
513        /**
514         * @see Infrastructure#getDataSqueezer()
515         */
516    
517        public DataSqueezer getDataSqueezer()
518        {
519            return _infrastructure.getDataSqueezer();
520        }
521    
522        /** @since 2.3 */
523    
524        public IPropertySource getPropertySource()
525        {
526            return _infrastructure.getApplicationPropertySource();
527        }
528    
529        /** @since 4.0 */
530        public Infrastructure getInfrastructure()
531        {
532            return _infrastructure;
533        }
534    
535        public String getOutputEncoding()
536        {
537            return _infrastructure.getOutputEncoding();
538        }
539    }