001// Licensed under the Apache License, Version 2.0 (the "License");
002// you may not use this file except in compliance with the License.
003// You may obtain a copy of the License at
004//
005// http://www.apache.org/licenses/LICENSE-2.0
006//
007// Unless required by applicable law or agreed to in writing, software
008// distributed under the License is distributed on an "AS IS" BASIS,
009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010// See the License for the specific language governing permissions and
011// limitations under the License.
012
013package org.apache.tapestry5.internal.services;
014
015import org.apache.tapestry5.ContextAwareException;
016import org.apache.tapestry5.ExceptionHandlerAssistant;
017import org.apache.tapestry5.Link;
018import org.apache.tapestry5.SymbolConstants;
019import org.apache.tapestry5.internal.InternalConstants;
020import org.apache.tapestry5.internal.structure.Page;
021import org.apache.tapestry5.ioc.ServiceResources;
022import org.apache.tapestry5.ioc.annotations.Symbol;
023import org.apache.tapestry5.ioc.internal.OperationException;
024import org.apache.tapestry5.ioc.util.ExceptionUtils;
025import org.apache.tapestry5.json.JSONObject;
026import org.apache.tapestry5.runtime.ComponentEventException;
027import org.apache.tapestry5.services.*;
028import org.slf4j.Logger;
029
030import javax.servlet.http.HttpServletResponse;
031import java.io.IOException;
032import java.io.OutputStream;
033import java.net.URLEncoder;
034import java.util.Arrays;
035import java.util.HashMap;
036import java.util.List;
037import java.util.Map;
038import java.util.Map.Entry;
039
040/**
041 * Default implementation of {@link RequestExceptionHandler} that displays the standard ExceptionReport page. Similarly to the
042 * servlet spec's standard error handling, the default exception handler allows configuring handlers for specific types of
043 * exceptions. The error-page/exception-type configuration in web.xml does not work in Tapestry application as errors are
044 * wrapped in Tapestry's exception types (see {@link OperationException} and {@link ComponentEventException} ).
045 * <p/>
046 * Configurations are flexible. You can either contribute a {@link ExceptionHandlerAssistant} to use arbitrary complex logic
047 * for error handling or a page class to render for the specific exception. Additionally, exceptions can carry context for the
048 * error page. Exception context is formed either from the name of Exception (e.g. SmtpNotRespondingException -> ServiceFailure mapping
049 * would render a page with URL /servicefailure/smtpnotresponding) or they can implement {@link ContextAwareException} interface.
050 * <p/>
051 * If no configured exception type is found, the default exception page {@link SymbolConstants#EXCEPTION_REPORT_PAGE} is rendered.
052 * This fallback exception page must implement the {@link org.apache.tapestry5.services.ExceptionReporter} interface.
053 */
054public class DefaultRequestExceptionHandler implements RequestExceptionHandler
055{
056    private final RequestPageCache pageCache;
057
058    private final PageResponseRenderer renderer;
059
060    private final Logger logger;
061
062    private final String pageName;
063
064    private final Request request;
065
066    private final Response response;
067
068    private final ComponentClassResolver componentClassResolver;
069
070    private final LinkSource linkSource;
071
072    private final ExceptionReporter exceptionReporter;
073
074    // should be Class<? extends Throwable>, Object but it's not allowed to configure subtypes
075    private final Map<Class, Object> configuration;
076
077    /**
078     * @param configuration
079     *         A map of Exception class and handler values. A handler is either a page class or an ExceptionHandlerAssistant. ExceptionHandlerAssistant can be a class
080     */
081    @SuppressWarnings("rawtypes")
082    public DefaultRequestExceptionHandler(RequestPageCache pageCache,
083                                          PageResponseRenderer renderer,
084                                          Logger logger,
085                                          @Symbol(SymbolConstants.EXCEPTION_REPORT_PAGE)
086                                          String pageName,
087                                          Request request,
088                                          Response response,
089                                          ComponentClassResolver componentClassResolver,
090                                          LinkSource linkSource,
091                                          ServiceResources serviceResources,
092                                          ExceptionReporter exceptionReporter,
093                                          Map<Class, Object> configuration)
094    {
095        this.pageCache = pageCache;
096        this.renderer = renderer;
097        this.logger = logger;
098        this.pageName = pageName;
099        this.request = request;
100        this.response = response;
101        this.componentClassResolver = componentClassResolver;
102        this.linkSource = linkSource;
103        this.exceptionReporter = exceptionReporter;
104
105        Map<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant> handlerAssistants = new HashMap<Class<ExceptionHandlerAssistant>, ExceptionHandlerAssistant>();
106
107        for (Entry<Class, Object> entry : configuration.entrySet())
108        {
109            if (!Throwable.class.isAssignableFrom(entry.getKey()))
110                throw new IllegalArgumentException(Throwable.class.getName() + " is the only allowable key type but " + entry.getKey().getName()
111                        + " was contributed");
112
113            if (entry.getValue() instanceof Class && ExceptionHandlerAssistant.class.isAssignableFrom((Class) entry.getValue()))
114            {
115                @SuppressWarnings("unchecked")
116                Class<ExceptionHandlerAssistant> handlerType = (Class<ExceptionHandlerAssistant>) entry.getValue();
117                ExceptionHandlerAssistant assistant = handlerAssistants.get(handlerType);
118                if (assistant == null)
119                {
120                    assistant = (ExceptionHandlerAssistant) serviceResources.autobuild(handlerType);
121                    handlerAssistants.put(handlerType, assistant);
122                }
123                entry.setValue(assistant);
124            }
125        }
126        this.configuration = configuration;
127    }
128
129    /**
130     * Handles the exception thrown at some point the request was being processed
131     * <p/>
132     * First checks if there was a specific exception handler/page configured for this exception type, it's super class or super-super class.
133     * Renders the default exception page if none was configured.
134     *
135     * @param exception
136     *         The exception that was thrown
137     */
138    @SuppressWarnings({"rawtypes", "unchecked"})
139    public void handleRequestException(Throwable exception) throws IOException
140    {
141        // skip handling of known exceptions if there are none configured
142        if (configuration.isEmpty())
143        {
144            renderException(exception);
145            return;
146        }
147
148        Throwable cause = exception;
149
150        // Depending on where the error was thrown, there could be several levels of wrappers..
151        // For exceptions in component operations, it's OperationException -> ComponentEventException -> <Target>Exception
152
153        // Throw away the wrapped exceptions first
154        while (cause instanceof OperationException || cause instanceof ComponentEventException)
155        {
156            if (cause.getCause() == null) break;
157            cause = cause.getCause();
158        }
159
160        Class<?> causeClass = cause.getClass();
161        if (!configuration.containsKey(causeClass))
162        {
163            // try at most two level of superclasses before delegating back to the default exception handler
164            causeClass = causeClass.getSuperclass();
165            if (causeClass == null || !configuration.containsKey(causeClass))
166            {
167                causeClass = causeClass.getSuperclass();
168                if (causeClass == null || !configuration.containsKey(causeClass))
169                {
170                    renderException(exception);
171                    return;
172                }
173            }
174        }
175
176        Object[] exceptionContext = formExceptionContext(cause);
177        Object value = configuration.get(causeClass);
178        Object page = null;
179        ExceptionHandlerAssistant assistant = null;
180        if (value instanceof ExceptionHandlerAssistant)
181        {
182            assistant = (ExceptionHandlerAssistant) value;
183            // in case the assistant changes the context
184            List context = Arrays.asList(exceptionContext);
185            page = assistant.handleRequestException(exception, context);
186            exceptionContext = context.toArray();
187        } else if (!(value instanceof Class))
188        {
189            renderException(exception);
190            return;
191        } else page = value;
192
193        if (page == null) return;
194
195        try
196        {
197            if (page instanceof Class)
198                page = componentClassResolver.resolvePageClassNameToPageName(((Class) page).getName());
199
200            Link link = page instanceof Link
201                    ? (Link) page
202                    : linkSource.createPageRenderLink(page.toString(), false, exceptionContext);
203
204            if (request.isXHR())
205            {
206                OutputStream os = response.getOutputStream("application/json;charset=UTF-8");
207
208                JSONObject reply = new JSONObject();
209                reply.in(InternalConstants.PARTIAL_KEY).put("redirectURL", link.toAbsoluteURI());
210
211                os.write(reply.toCompactString().getBytes("UTF-8"));
212
213                os.close();
214
215                return;
216            }
217
218            // Normal behavior is just a redirect.
219
220            response.sendRedirect(link);
221        }
222        // The above could throw an exception if we are already on a render request, but it's
223        // user's responsibility not to abuse the mechanism
224        catch (Exception e)
225        {
226            logger.warn(String.format("A new exception was thrown while trying to handle an instance of %s.",
227                    exception.getClass().getName()), e);
228            // Nothing to do but delegate
229            renderException(exception);
230        }
231    }
232
233    private void renderException(Throwable exception) throws IOException
234    {
235        logger.error(String.format("Processing of request failed with uncaught exception: %s", exception), exception);
236
237        // In the case where one of the contributed rules, above, changes the behavior, then we don't report the
238        // exception. This is just for exceptions that are going to be rendered, real failures.
239        exceptionReporter.reportException(exception);
240
241        // TAP5-233: Make sure the client knows that an error occurred.
242
243        response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
244
245        String rawMessage = ExceptionUtils.toMessage(exception);
246
247        // Encode it compatibly with the JavaScript escape() function.
248
249        String encoded = URLEncoder.encode(rawMessage, "UTF-8").replace("+", "%20");
250
251        response.setHeader("X-Tapestry-ErrorMessage", encoded);
252
253        Page page = pageCache.get(pageName);
254
255        org.apache.tapestry5.services.ExceptionReporter rootComponent = (org.apache.tapestry5.services.ExceptionReporter) page.getRootComponent();
256
257        // Let the page set up for the new exception.
258
259        rootComponent.reportException(exception);
260
261        renderer.renderPageResponse(page);
262    }
263
264    /**
265     * Form exception context either from the name of the exception, or the context the exception contains if it's of type
266     * {@link ContextAwareException}
267     *
268     * @param exception
269     *         The exception that the context is formed for
270     * @return Returns an array of objects to be used as the exception context
271     */
272    @SuppressWarnings({"unchecked", "rawtypes"})
273    protected Object[] formExceptionContext(Throwable exception)
274    {
275        if (exception instanceof ContextAwareException) return ((ContextAwareException) exception).getContext();
276
277        Class exceptionClass = exception.getClass();
278        // pick the first class in the hierarchy that's not anonymous, probably no reason check for array types
279        while ("".equals(exceptionClass.getSimpleName()))
280            exceptionClass = exceptionClass.getSuperclass();
281
282        // check if exception type is plain runtimeException - yes, we really want the test to be this way
283        if (exceptionClass.isAssignableFrom(RuntimeException.class))
284            return exception.getMessage() == null ? new Object[0] : new Object[]{exception.getMessage().toLowerCase()};
285
286        // otherwise, form the context from the exception type name
287        String exceptionType = exceptionClass.getSimpleName();
288        if (exceptionType.endsWith("Exception")) exceptionType = exceptionType.substring(0, exceptionType.length() - 9);
289        return new Object[]{exceptionType.toLowerCase()};
290    }
291
292}