001// Copyright 2023 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
015package org.apache.tapestry5.internal;
016
017import java.io.IOException;
018import java.util.List;
019
020import org.apache.tapestry5.ComponentResources;
021import org.apache.tapestry5.ExceptionHandlerAssistant;
022import org.apache.tapestry5.SymbolConstants;
023import org.apache.tapestry5.corelib.components.Form;
024import org.apache.tapestry5.services.ComponentSource;
025import org.apache.tapestry5.services.PageRenderLinkSource;
026import org.apache.tapestry5.services.RequestExceptionHandler;
027
028/**
029 * Handles {@link FormsRequirePostException}s (thrown by the {@link Form} component when the request method was
030 * other than post) by redirecting to the page containing the form.
031 * <p>
032 * This assistant is contributed to the default {@link RequestExceptionHandler} service in a way that it is
033 * effective only in production mode.
034 * 
035 * @see ExceptionHandlerAssistant
036 * @see RequestExceptionHandler
037 * @see SymbolConstants#PRODUCTION_MODE
038 * @since 5.8.3
039 */
040public class FormsRequirePostExceptionHandlerAssistant implements ExceptionHandlerAssistant
041{
042    final ComponentSource componentSource;
043
044    final PageRenderLinkSource linkSource;
045
046    public FormsRequirePostExceptionHandlerAssistant(final ComponentSource componentSource, final PageRenderLinkSource linkSource)
047    {
048        this.componentSource = componentSource;
049        this.linkSource = linkSource;
050    }
051
052    @Override
053    public Object handleRequestException(Throwable exception, List<Object> exceptionContext) throws IOException
054    {
055        ComponentResources cr = componentSource.getActivePage().getComponentResources();
056
057        String pageName = cr.getPageName();
058
059        return linkSource.createPageRenderLink(pageName);
060    }
061}