Protecting Pages

Let's say you would like Tapestry to protect particular pages from being accessed by users who have not logged in...

In JumpStart we do this with 2 parts. First, we create an annotation, @ProtectedPage, which we add to pages we want to protect.
You should consider doing the opposite: create an annotation @PublicPage to put on the pages you want to be public and protect all others.

Second, we create a ComponentRequestFilter, called PageProtectionFilter, which we contribute to the application in AppModule. This filter inspects every render request and component event request as it comes in, determines which page is involved, and whether the page has the annotation. If it does and the user is not logged in, then the filter redirects the browser to the Login page. It also tells the Login page which page you were trying to reach.
Here's a link to a "protected" page: View admin user. Try it!
For more elaborate security try tapestry-security and Security in Tapestry5HowTos.

References: Request Processing diagram, Securing Tapestry Pages with Annotations, ComponentRequestFilter, Request.

Home

ProtectingPages.tml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- We need a doctype to allow us to use special characters like &nbsp; 
     We use a "strict" DTD to make IE follow the alignment rules. -->
     
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
<head>
    <link rel="stylesheet" type="text/css" href="${context:css/examples/examples.css}"/>
</head>
<body>
    <h1>Protecting Pages</h1>
    
    Let's say you would like Tapestry to protect particular pages from being accessed by users who have not logged in...<br/><br/>
    
    In JumpStart we do this with 2 parts. First, we create an annotation, @ProtectedPage, which we add to pages we want to protect.<br/> 
    You should consider doing the opposite: create an annotation @PublicPage to put on the pages you want to be public and protect all others.<br/><br/>
    
    Second, we create a ComponentRequestFilter, called PageProtectionFilter, which we contribute to the application in AppModule. 
    This filter inspects every <a href="http://tapestry.apache.org/page-navigation.html#PageNavigation-PageRenderRequests">
    render request</a> and <a href="http://tapestry.apache.org/page-navigation.html#PageNavigation-ComponentEventRequests">
    component event request</a> as it comes in, determines which page is involved,
    and whether the page has the annotation. If it does and the user is not logged in, then the filter redirects the browser to 
    the Login page. It also tells the Login page which page you were trying to reach.

    <div class="eg">
        Here's a link to a "protected" page: 
        <a t:type="pagelink" t:page="theapp/security/userview" t:context="literal:2">View admin user</a>. Try it!
    </div>
    
    For more elaborate security try <a href="http://tynamo.org/tapestry-security+guide">tapestry-security</a> 
    and <a href="http://wiki.apache.org/tapestry/Tapestry5HowTos#Security">Security in Tapestry5HowTos</a>.<br/><br/>
    
    References: 
    <a href="http://tapestry.apache.org/request-processing.html#RequestProcessing-Overview">Request Processing diagram</a>, 
    <a href="http://tapestryjava.blogspot.com/2009/12/securing-tapestry-pages-with.html">Securing Tapestry Pages with Annotations</a>, 
    <a href="http://tapestry.apache.org/5.3/apidocs/org/apache/tapestry5/services/ComponentRequestFilter.html">ComponentRequestFilter</a>, 
    <a href="http://tapestry.apache.org/5.3/apidocs/org/apache/tapestry5/services/Request.html">Request</a>.<br/><br/>
    
    <a t:type="pagelink" t:page="Index" href="#">Home</a><br/><br/>
    
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/pages/examples/infrastructure/ProtectingPages.tml"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/pages/examples/infrastructure/ProtectingPages.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/css/examples/examples.css"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/pages/theapp/security/UserView.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/annotation/ProtectedPage.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/services/PageProtectionFilter.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/pages/infra/PageDenied.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/pages/infra/PageDenied.tml"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/commons/IIntermediatePage.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/state/theapp/Visit.java"/>
    <t:sourcecodedisplay src="/web/src/main/java/jumpstart/web/services/AppModule.java"/>
</body>
</html>

ProtectingPages.java


package jumpstart.web.pages.examples.infrastructure;

public class ProtectingPages {
}

examples.css


body            { font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif; font-size: 13px; font-weight: normal; color: #333; line-height: 17px; }
h1              { font-size: 26px; line-height: 20px; } /* For IE 7 */
form            { margin: 0; }                  

.eg             { margin: 20px 0; padding: 20px; color: #888; 
                    border: 1px solid #ddd; border-radius: 4px; -webkit-border-radius: 4px; -mox-border-radius: 4px; }

a               { text-decoration: none; color: #3D69B6; }
a:hover         { text-decoration: underline; }

/* For BeanDisplay */
.eg dl          { margin: 0; color: #333; }
.eg dl.t-beandisplay dd.id  { display: inline; margin-left: 0px; }  /* IE 7 hack */

UserView.java


package jumpstart.web.pages.theapp.security;

import java.util.List;

import javax.ejb.EJB;

import jumpstart.business.commons.exception.BusinessException;
import jumpstart.business.commons.exception.DoesNotExistException;
import jumpstart.business.domain.security.User;
import jumpstart.business.domain.security.User.PageStyle;
import jumpstart.business.domain.security.UserRole;
import jumpstart.business.domain.security.iface.ISecurityFinderServiceLocal;
import jumpstart.web.annotation.ProtectedPage;
import jumpstart.web.base.theapp.SimpleBasePage;

import org.apache.tapestry5.Link;
import org.apache.tapestry5.annotations.InjectPage;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.services.TypeCoercer;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.util.EnumValueEncoder;

@ProtectedPage
public class UserView extends SimpleBasePage {

    // Activation context

    private Long userId;

    // Screen fields

    @Property
    private User user;

    @Property
    private List<UserRole> userRoles;

    @Property
    private UserRole userRole;

    // Other pages

    @InjectPage
    private UserSearch userSearch;

    @InjectPage
    private UserRoleView viewPage;

    // Generally useful bits and pieces

    @EJB
    private ISecurityFinderServiceLocal securityFinderService;

    @Inject
    private PageRenderLinkSource pageRenderLinkSource;

    @Inject
    private TypeCoercer typeCoercer;

    // The code

    public void set(Long userId) {
        this.userId = userId;
    }

    Long onPassivate() {
        return userId;
    }

    void onActivate(Long userId) {
        this.userId = userId;
    }

    void setupRender() throws BusinessException {
        try {
            user = securityFinderService.findUser(userId);
        }
        catch (DoesNotExistException e) {
            // Handle null user in the template
        }

        userRoles = securityFinderService.findUserRolesShallowishByUser(userId);
    }

    void onRefresh() {
    }

    Link onCancel() {
        return userSearch.createLinkWithLastSearch();
    }

    Object onViewUserRole(Long id) {
        viewPage.set(id, createLinkToThisPage());
        return viewPage;
    }

    private Link createLinkToThisPage() {
        Link thisPageLink = pageRenderLinkSource.createPageRenderLinkWithContext(this.getClass(), onPassivate());
        return thisPageLink;
    }

    public PageStyle getBoxy() {
        return User.PageStyle.BOXY;
    }

    public PageStyle getWide() {
        return User.PageStyle.WIDE;
    }

    public EnumValueEncoder<PageStyle> getPageStyleEncoder() {
        return new EnumValueEncoder<PageStyle>(typeCoercer, User.PageStyle.class);
    }
}

ProtectedPage.java


// Based on http://wiki.apache.org/tapestry/Tapestry5HowToControlAccess
// When you apply this @ProtectedPage annotation to any page class that you want 

package jumpstart.web.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * Specifies that the class is a "protected page", one that must not be accessible by users that are not logged in.
 * This annotation is applied to a Tapestry page class. The protection is provided by {@link PageProtectionFilter}. 
 */
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ProtectedPage {
}

PageProtectionFilter.java


// Based on http://tapestryjava.blogspot.com/2009/12/securing-tapestry-pages-with.html

package jumpstart.web.services;

import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

import javax.annotation.security.RolesAllowed;

import jumpstart.business.domain.security.User;
import jumpstart.business.domain.security.iface.ISecurityFinderServiceLocal;
import jumpstart.client.BusinessServicesLocator;
import jumpstart.client.IBusinessServicesLocator;
import jumpstart.web.annotation.ProtectedPage;
import jumpstart.web.commons.IIntermediatePage;
import jumpstart.web.pages.infra.PageDenied;
import jumpstart.web.pages.theapp.Login;
import jumpstart.web.state.theapp.Visit;

import org.apache.tapestry5.EventContext;
import org.apache.tapestry5.Link;
import org.apache.tapestry5.internal.EmptyEventContext;
import org.apache.tapestry5.runtime.Component;
import org.apache.tapestry5.services.ApplicationStateManager;
import org.apache.tapestry5.services.ComponentEventRequestParameters;
import org.apache.tapestry5.services.ComponentRequestFilter;
import org.apache.tapestry5.services.ComponentRequestHandler;
import org.apache.tapestry5.services.ComponentSource;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.PageRenderRequestParameters;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.Response;
import org.slf4j.Logger;

/**
 * A service that protects pages annotated with {@link jumpstart.web.annotation.ProtectedPage}. It examines each
 * {@link org.apache.tapestry5.services.Request} and redirects it to the login page if the request is for a
 * ProtectedPage and the user is not logged in. If the page also has the {@link javax.annotation.security.RolesAllowed}
 * annotation then the user must belong to one of the listed roles.
 * <p>
 * To use this filter, contribute it to Tapestry's ComponentRequestHandler service as we do in AppModule.
 * 
 */
public class PageProtectionFilter implements ComponentRequestFilter {
    private static final String COMPONENT_PARAM_PREFIX = "t:";

    private final String autoLoginStr = System.getProperty("jumpstart.auto-login");

    private enum AuthCheckResult {
        AUTHORISED, DENIED, RELOAD_XHR, AUTHENTICATE;
    }

    private final PageRenderLinkSource pageRenderLinkSource;
    private final ComponentSource componentSource;
    private final Request request;
    private final Response response;
    private ApplicationStateManager sessionStateManager;
    private final Logger logger;
    private IBusinessServicesLocator businessServicesLocator;

    /**
     * Receive all the services needed as constructor arguments. When we bind this service, T5 IoC will provide all the
     * services.
     */
    public PageProtectionFilter(PageRenderLinkSource pageRenderLinkSource, ComponentSource componentSource,
            Request request, Response response, ApplicationStateManager asm, Logger logger) {
        this.pageRenderLinkSource = pageRenderLinkSource;
        this.request = request;
        this.response = response;
        this.componentSource = componentSource;
        this.sessionStateManager = asm;
        this.logger = logger;
        this.businessServicesLocator = null;
    }

    @Override
    public void handlePageRender(PageRenderRequestParameters parameters, ComponentRequestHandler handler)
            throws IOException {

        AuthCheckResult result = checkAuthorityToPage(parameters.getLogicalPageName());

        if (result == AuthCheckResult.AUTHORISED) {
            handler.handlePageRender(parameters);
        }
        else if (result == AuthCheckResult.DENIED) {
            // The method will have set the response to redirect to the PageDenied page.
            return;
        }
        else if (result == AuthCheckResult.AUTHENTICATE) {

            // Redirect to the Login page, with memory of the request.

            Link requestedPageLink = createLinkToRequestedPage(parameters.getLogicalPageName(),
                    parameters.getActivationContext());
            Link loginPageLink = createLoginPageLinkWithMemory(requestedPageLink);

            response.sendRedirect(loginPageLink);
        }
        else {
            throw new IllegalStateException(result.toString());
        }

    }

    @Override
    public void handleComponentEvent(ComponentEventRequestParameters parameters, ComponentRequestHandler handler)
            throws IOException {

        AuthCheckResult result = checkAuthorityToPage(parameters.getActivePageName());

        if (result == AuthCheckResult.AUTHORISED) {
            handler.handleComponentEvent(parameters);
        }
        else if (result == AuthCheckResult.DENIED) {
            // The method will have set the response to redirect to the PageDenied page.
            return;
        }
        else if (result == AuthCheckResult.RELOAD_XHR) {
            
            // Return an AJAX response that reloads the page.
            
            Link requestedPageLink = createLinkToRequestedPage(parameters.getActivePageName(),
                    parameters.getPageActivationContext());
            OutputStream os = response.getOutputStream("application/json;charset=UTF-8");
            os.write(("{\"redirectURL\":\"" + requestedPageLink.toAbsoluteURI() + "\"}").getBytes());
            os.close();
            return;
        }
        else if (result == AuthCheckResult.AUTHENTICATE) {

            // Redirect to the Login page, with memory of the request.

            Link requestedPageLink = createLinkToRequestedPage(parameters.getActivePageName(),
                    parameters.getPageActivationContext());
            Link loginPageLink = createLoginPageLinkWithMemory(requestedPageLink);

            response.sendRedirect(loginPageLink);
        }
        else {
            throw new IllegalStateException(result.toString());
        }

    }

    public AuthCheckResult checkAuthorityToPage(String requestedPageName) throws IOException {

        // Does the page have security annotations @ProtectedPage or @RolesAllowed?

        Component page = componentSource.getPage(requestedPageName);
        boolean protectedPage = page.getClass().getAnnotation(ProtectedPage.class) != null;
        RolesAllowed rolesAllowed = page.getClass().getAnnotation(RolesAllowed.class);

        // If the security annotations on the page conflict in meaning, then error

        if (rolesAllowed != null && !protectedPage) {
            throw new IllegalStateException("Page \"" + requestedPageName
                    + "\" is annotated with @RolesAllowed but not @ProtectedPage.");
        }

        // If page is public (ie. not protected), then everyone is authorised to it so allow access

        if (!protectedPage) {
            return AuthCheckResult.AUTHORISED;
        }

        // If request is AJAX with no session, return an AJAX response that forces reload of the page

        if (request.isXHR() && request.getSession(false) == null) {
            return AuthCheckResult.RELOAD_XHR;
        }

        // If user has not been authenticated, disallow.

        if (!isAuthenticated()) {
            return AuthCheckResult.AUTHENTICATE;
        }

        // If user is authorised to the page, then all is well.

        if (isAuthorised(rolesAllowed)) {
            return AuthCheckResult.AUTHORISED;
        }

        // Fell through, so redirect to the PageDenied page.

        Link pageProtectedLink = pageRenderLinkSource.createPageRenderLinkWithContext(PageDenied.class,
                requestedPageName);
        response.sendRedirect(pageProtectedLink);
        return AuthCheckResult.DENIED;

    }

    private Link createLinkToRequestedPage(String requestedPageName, EventContext eventContext) {

        // Create a link to the page you wanted.

        Link linkToRequestedPage;

        if (eventContext instanceof EmptyEventContext) {
            linkToRequestedPage = pageRenderLinkSource.createPageRenderLink(requestedPageName);
        }
        else {
            Object[] args = new String[eventContext.getCount()];
            for (int i = 0; i < eventContext.getCount(); i++) {
                args[i] = eventContext.get(String.class, i);
            }
            linkToRequestedPage = pageRenderLinkSource.createPageRenderLinkWithContext(requestedPageName, args);
        }

        // Add any activation request parameters (AKA query parameters).

        List<String> parameterNames = request.getParameterNames();

        for (String parameterName : parameterNames) {
            linkToRequestedPage.removeParameter(parameterName);
            if (!parameterName.startsWith(COMPONENT_PARAM_PREFIX)) {
                linkToRequestedPage.addParameter(parameterName, request.getParameter(parameterName));
            }
        }

        return linkToRequestedPage;
    }

    private boolean isAuthenticated() throws IOException {

        // If a Visit already exists in the session then you have already been authenticated

        if (sessionStateManager.exists(Visit.class)) {
            return true;
        }

        // Else if "auto-login" is on, try auto-logging in.
        // - this facility is for development environment only. It avoids getting you thrown out of the
        // app every time the session clears eg. when app is restarted.

        else {
            if (isAutoLoginOn()) {
                autoLogin(1L);
                return true;
            }
        }

        return false;
    }

    private boolean isAuthorised(RolesAllowed rolesAllowed) throws IOException {
        boolean authorised = false;

        if (rolesAllowed == null) {
            authorised = true;
        }
        else {
            // Here we could check whether the user's role, or perhaps roles, include one of the rolesAllowed.
            // Typically we'd cache the user's roles in the Visit.
        }

        return authorised;
    }

    /**
     * Checks the value of system property jumpstart.auto-login. If "true" then returns true; if "false" then return
     * false; if not set then returns false.
     */
    private boolean isAutoLoginOn() {
        boolean autoLogin = false;
        if (autoLoginStr == null) {
            autoLogin = false;
        }
        else if (autoLoginStr.equalsIgnoreCase("true")) {
            autoLogin = true;
        }
        else if (autoLoginStr.equalsIgnoreCase("false")) {
            autoLogin = false;
        }
        else {
            throw new IllegalStateException(
                    "System property jumpstart.auto-login has been set to \""
                            + autoLoginStr
                            + "\".  Please set it to \"true\" or \"false\".  If not specified at all then it will default to \"false\".");
        }
        return autoLogin;
    }

    /**
     * Automatically logs you in as the given user. Intended for use in development environment only.
     */
    private void autoLogin(Long userId) {

        // Lazy-load the business services locator because it is only needed for auto-login

        if (businessServicesLocator == null) {
            businessServicesLocator = new BusinessServicesLocator(logger);
        }

        try {
            User user = getSecurityFinderService().findUser(userId);

            Visit visit = new Visit(user);
            logger.info(user.getLoginId() + " has been auto-logged-in.");

            sessionStateManager.set(Visit.class, visit);
        }
        catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }

    private Link createLoginPageLinkWithMemory(Link requestedPageLink) {

        IIntermediatePage loginPage = (IIntermediatePage) componentSource.getPage(Login.class);
        loginPage.setNextPageLink(requestedPageLink);
        Link loginPageLink = pageRenderLinkSource.createPageRenderLink(Login.class);

        return loginPageLink;
    }

    private ISecurityFinderServiceLocal getSecurityFinderService() {
        return (ISecurityFinderServiceLocal) businessServicesLocator.getService(ISecurityFinderServiceLocal.class);
    }
}

PageDenied.java


package jumpstart.web.pages.infra;

import javax.servlet.http.HttpServletResponse;

import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Response;

/**
 * Intended for use with PageProtectionFilter, this displays the path of the page to which you are not authorised.
 */
public class PageDenied {

    // Activation context

    @Property
    private String urlDenied;

    // Other useful bits and pieces

    @Inject
    private Response response;

    // The code

    String onPassivate() {
        return urlDenied;
    }

    void onActivate(String urlDenied) {
        this.urlDenied = urlDenied;
    }

    public void setupRender() {
        response.setStatus(HttpServletResponse.SC_NOT_FOUND);
    }

}

PageDenied.tml


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- We need a doctype to allow us to use special characters like &nbsp; 
     We use a "strict" DTD to make IE follow the alignment rules. -->
     
<html xmlns:t="http://tapestry.apache.org/schema/tapestry_5_3.xsd">
<head>
    <title>Page Denied</title>
</head>
<body>
    <h1>Page Denied</h1>
    
    You are not authorised to page ${urlDenied}.<br/><br/>
    
    <a t:type="pageLink" t:page="Index">Home</a>
</body>
</html>

IIntermediatePage.java


package jumpstart.web.commons;

import org.apache.tapestry5.Link;

public interface IIntermediatePage {
    
    void setNextPageLink(Link nextPageLink);

}

Visit.java


package jumpstart.web.state.theapp;

import java.io.Serializable;

import jumpstart.business.domain.security.User;
import jumpstart.business.domain.security.User.PageStyle;

@SuppressWarnings("serial")
public class Visit implements Serializable {

    private Long myUserId = null;
    private String myLoginId = null;
    private PageStyle pageStyle = null;
    private String dateInputPattern = null;
    private String dateViewPattern = null;
    private String dateListPattern = null;
    
    public Visit(User user) {
        myUserId = user.getId();
        cacheUsefulStuff(user);
    }

    public void noteChanges(User user) {
        if (user == null) {
            throw new IllegalArgumentException();
        }
        else if (user.getId().equals(myUserId)) {
            cacheUsefulStuff(user);
        }
    }

    private void cacheUsefulStuff(User user) {
        myLoginId = user.getLoginId();
        pageStyle = user.getPageStyle();
        dateInputPattern = user.getDateInputPattern();
        dateViewPattern = user.getDateViewPattern();
        dateListPattern = user.getDateListPattern();
    }

    public Long getMyUserId() {
        return myUserId;
    }

    public String getMyLoginId() {
        return myLoginId;
    }

    public PageStyle getPageStyle() {
        return pageStyle;
    }

    public String getDateInputPattern() {
        return dateInputPattern;
    }

    public String getDateViewPattern() {
        return dateViewPattern;
    }

    public String getDateListPattern() {
        return dateListPattern;
    }

}

AppModule.java


package jumpstart.web.services;

import java.util.Arrays;
import java.util.HashSet;

import jumpstart.util.JodaTimeUtil;
import jumpstart.web.translators.MoneyTranslator;
import jumpstart.web.translators.YesNoTranslator;
import jumpstart.web.validators.Letters;

import org.apache.tapestry5.SymbolConstants;
import org.apache.tapestry5.Translator;
import org.apache.tapestry5.Validator;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.ioc.Configuration;
import org.apache.tapestry5.ioc.MappedConfiguration;
import org.apache.tapestry5.ioc.OrderedConfiguration;
import org.apache.tapestry5.ioc.ServiceBinder;
import org.apache.tapestry5.ioc.annotations.EagerLoad;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.ioc.annotations.Primary;
import org.apache.tapestry5.ioc.annotations.Symbol;
import org.apache.tapestry5.ioc.services.ClasspathURLConverter;
import org.apache.tapestry5.ioc.services.Coercion;
import org.apache.tapestry5.ioc.services.CoercionTuple;
import org.apache.tapestry5.ioc.services.ThreadLocale;
import org.apache.tapestry5.services.BeanBlockContribution;
import org.apache.tapestry5.services.ComponentRequestFilter;
import org.apache.tapestry5.services.DisplayBlockContribution;
import org.apache.tapestry5.services.EditBlockContribution;
import org.apache.tapestry5.services.PageRenderLinkSource;
import org.apache.tapestry5.services.Request;
import org.apache.tapestry5.services.RequestFilter;
import org.apache.tapestry5.services.security.WhitelistAnalyzer;
import org.apache.tapestry5.services.transform.ComponentClassTransformWorker2;
import org.apache.tapestry5.upload.services.UploadSymbols;
import org.got5.tapestry5.jquery.JQuerySymbolConstants;
import org.joda.time.DateMidnight;
import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.LocalDateTime;
import org.joda.time.LocalTime;
import org.slf4j.Logger;

/**
 * This module is automatically included as part of the Tapestry IoC Registry, it's a good place to configure and extend
 * Tapestry, or to place your own service definitions. See http://tapestry.apache.org/5.3.4/tapestry-ioc/module.html
 */
public class AppModule {
    private static final String UPLOADS_PATH = "jumpstart.upload-path";

    @Inject
    @Symbol(SymbolConstants.PRODUCTION_MODE)
    @Property(write = false)
    private static boolean productionMode;

    // Add 2 services to those provided by Tapestry.
    // - CountryNames, and SelectIdModelFactory are used by pages which ask Tapestry to @Inject them.

    public static void bind(ServiceBinder binder) {
        binder.bind(CountryNames.class);
        binder.bind(SelectIdModelFactory.class, SelectIdModelFactoryImpl.class);

        // This next line addresses an issue affecting GlassFish and JBoss - see http://blog.progs.be/?p=52
        javassist.runtime.Desc.useContextClassLoader = true;
    }

    // Tell Tapestry about our custom translators, validators, and their message files.
    // We do this by contributing configuration to Tapestry's TranslatorAlternatesSource service, FieldValidatorSource
    // service, and ComponentMessagesSource service.

    @SuppressWarnings("rawtypes")
    public static void contributeTranslatorAlternatesSource(MappedConfiguration<String, Translator> configuration,
            ThreadLocale threadLocale) {
        configuration.add("yesno", new YesNoTranslator("yesno"));
        configuration.add("money2", new MoneyTranslator("money2", 2, threadLocale));
    }

    @SuppressWarnings("rawtypes")
    public static void contributeFieldValidatorSource(MappedConfiguration<String, Validator> configuration) {
        configuration.add("letters", new Letters());
    }

    public void contributeComponentMessagesSource(OrderedConfiguration<String> configuration) {
        configuration.add("myTranslationMessages", "jumpstart/web/translators/TranslationMessages");
        configuration.add("myValidationMessages", "jumpstart/web/validators/ValidationMessages");
    }

    // Tell Tapestry about our custom ValueEncoders.
    // We do this by contributing configuration to Tapestry's ValueEncoderSource service.

    // @SuppressWarnings("rawtypes")
    // public static void contributeValueEncoderSource(MappedConfiguration<Class, Object> configuration) {
    // configuration.addInstance(Person.class, PersonEncoder.class);
    // }

    // Tell Tapestry which locales we support, and tell Tapestry5jQuery not to suppress Tapestry's built-in Prototype
    // and Scriptaculous (see the JQuery example for more information).
    // We do this by contributing configuration to Tapestry's ApplicationDefaults service.

    public static void contributeApplicationDefaults(MappedConfiguration<String, String> configuration) {
        configuration.add(SymbolConstants.SUPPORTED_LOCALES, "en_US,en_GB,fr");
        // We have Tapestry5jQuery installed. Tell it we don't want it to suppress Prototype and Scriptaculous.
        configuration.add(JQuerySymbolConstants.SUPPRESS_PROTOTYPE, "false");
        // We don't use $j in our javascript - instead we use function scoping (see
        // http://api.jquery.com/jQuery.noConflict/)
        // but we need this next line to keep Tapestry happy (since Tapestry 5.3.4).
        configuration.add(JQuerySymbolConstants.JQUERY_ALIAS, "$j");
    }

    // Tell Tapestry how to block access to WEB-INF/, META-INF/, and assets that are not in our assets "whitelist".
    // We do this by contributing a custom RequestFilter to Tapestry's RequestHandler service.
    // - This is necessary due to https://issues.apache.org/jira/browse/TAP5-815 .
    // - RequestHandler is shown in http://tapestry.apache.org/request-processing.html#RequestProcessing-Overview .
    // - RequestHandler is described in http://tapestry.apache.org/request-processing.html
    // - Based on an entry in the Tapestry Users mailing list by martijn.list on 15 Aug 09.

    public void contributeRequestHandler(OrderedConfiguration<RequestFilter> configuration,
            PageRenderLinkSource pageRenderLinkSource) {
        final HashSet<String> ASSETS_WHITE_LIST = new HashSet<String>(Arrays.asList("jpg", "jpeg", "png", "gif", "js",
                "css", "ico"));
        configuration.add("AssetProtectionFilter", new AssetProtectionFilter(ASSETS_WHITE_LIST, pageRenderLinkSource),
                "before:*");
    }

    // Tell Tapestry how to detect and protect pages that require security.
    // We do this by contributing a custom ComponentRequestFilter to Tapestry's ComponentRequestHandler service.
    // - ComponentRequestHandler is shown in
    // http://tapestry.apache.org/request-processing.html#RequestProcessing-Overview
    // - Based on http://tapestryjava.blogspot.com/2009/12/securing-tapestry-pages-with.html

    public void contributeComponentRequestHandler(OrderedConfiguration<ComponentRequestFilter> configuration) {
        configuration.addInstance("PageProtectionFilter", PageProtectionFilter.class);
    }

    // Tell Tapestry how to handle JBoss 7's classpath URLs - JBoss uses a "virtual file system".
    // See "Running Tapestry on JBoss" in http://wiki.apache.org/tapestry/Tapestry5HowTos .

    @SuppressWarnings("rawtypes")
    public static void contributeServiceOverride(MappedConfiguration<Class, Object> configuration) {
        configuration.add(ClasspathURLConverter.class, new ClasspathURLConverterJBoss7());
    }

    // Tell Tapestry how to handle @EJB in page and component classes.
    // We do this by contributing configuration to Tapestry's ComponentClassTransformWorker service.
    // - Based on http://wiki.apache.org/tapestry/JEE-Annotation.

    @Primary
    public static void contributeComponentClassTransformWorker(
            OrderedConfiguration<ComponentClassTransformWorker2> configuration) {
        configuration.addInstance("EJB", EJBAnnotationWorker.class, "before:Property");
    }

    // Tell Tapestry how to handle pages annotated with @WhitelistAccessOnly, eg. Tapestry's ServiceStatus and
    // PageCatalog.
    // The default WhitelistAnalyzer allows localhost only and only in non-production mode.
    // Our aim is to make the servicestatus page available to ALL clients when not in production mode.
    // We do this by contributing our own WhitelistAnalyzer to Tapestry's ClientWhitelist service.

    public static void contributeClientWhitelist(OrderedConfiguration<WhitelistAnalyzer> configuration) {
        if (!productionMode) {
            configuration.add("NonProductionWhitelistAnalyzer", new WhitelistAnalyzer() {
                @Override
                public boolean isRequestOnWhitelist(Request request) {
                    if (request.getPath().startsWith("/core/servicestatus")) {
                        return true;
                    }
                    else {
                        // This is copied from org.apache.tapestry5.internal.services.security.LocalhostOnly
                        String remoteHost = request.getRemoteHost();
                        return remoteHost.equals("localhost") || remoteHost.equals("127.0.0.1")
                                || remoteHost.equals("0:0:0:0:0:0:0:1%0") || remoteHost.equals("0:0:0:0:0:0:0:1");
                    }
                }
            }, "before:*");
        }
    }

    // Tell Tapestry how to build our Filer service (used in the FileUpload example).
    // Annotate it with EagerLoad to force resolution of symbols at startup rather than when it is first used.

    @EagerLoad
    public static IFiler buildFiler(Logger logger, @Inject @Symbol(UPLOADS_PATH) final String uploadsPath,
            @Inject @Symbol(UploadSymbols.FILESIZE_MAX) final long fileSizeMax) {
        return new Filer(logger, UPLOADS_PATH, uploadsPath, UploadSymbols.FILESIZE_MAX, fileSizeMax);
    }

    // Tell Tapestry how to coerce Joda Time types to and from Java Date types for the TypeCoercers example.
    // We do this by contributing configuration to Tapestry's TypeCoercer service.
    // - Based on http://tapestry.apache.org/typecoercer-service.html

    @SuppressWarnings("rawtypes")
    public static void contributeTypeCoercer(Configuration<CoercionTuple> configuration) {

        // From java.util.Date to DateMidnight

        Coercion<java.util.Date, DateMidnight> toDateMidnight = new Coercion<java.util.Date, DateMidnight>() {
            public DateMidnight coerce(java.util.Date input) {
                // TODO - confirm this conversion always works, esp. across timezones
                return JodaTimeUtil.toDateMidnight(input);
            }
        };

        configuration.add(new CoercionTuple<>(java.util.Date.class, DateMidnight.class, toDateMidnight));

        // From DateMidnight to java.util.Date

        Coercion<DateMidnight, java.util.Date> fromDateMidnight = new Coercion<DateMidnight, java.util.Date>() {
            public java.util.Date coerce(DateMidnight input) {
                // TODO - confirm this conversion always works, esp. across timezones
                return JodaTimeUtil.toJavaDate(input);
            }
        };

        configuration.add(new CoercionTuple<>(DateMidnight.class, java.util.Date.class, fromDateMidnight));

        // From java.util.Date to LocalDate

        Coercion<java.util.Date, LocalDate> toLocalDate = new Coercion<java.util.Date, LocalDate>() {
            public LocalDate coerce(java.util.Date input) {
                // TODO - confirm this conversion always works, esp. across timezones
                return JodaTimeUtil.toLocalDate(input);
            }
        };

        configuration.add(new CoercionTuple<>(java.util.Date.class, LocalDate.class, toLocalDate));

        // From LocalDate to java.util.Date

        Coercion<LocalDate, java.util.Date> fromLocalDate = new Coercion<LocalDate, java.util.Date>() {
            public java.util.Date coerce(LocalDate input) {
                // TODO - confirm this conversion always works, esp. across timezones
                return JodaTimeUtil.toJavaDate(input);
            }
        };

        configuration.add(new CoercionTuple<>(LocalDate.class, java.util.Date.class, fromLocalDate));
    }

    // Tell Tapestry how its BeanDisplay and BeanEditor can handle the JodaTime types.
    // We do this by contributing configuration to Tapestry's DefaultDataTypeAnalyzer and BeanBlockSource services.
    // - Based on http://tapestry.apache.org/beaneditform-guide.html .

    public static void contributeDefaultDataTypeAnalyzer(
            @SuppressWarnings("rawtypes") MappedConfiguration<Class, String> configuration) {
        configuration.add(DateTime.class, "dateTime");
        configuration.add(DateMidnight.class, "dateMidnight");
        configuration.add(LocalDateTime.class, "localDateTime");
        configuration.add(LocalDate.class, "localDate");
        configuration.add(LocalTime.class, "localTime");
    }

    public static void contributeBeanBlockSource(Configuration<BeanBlockContribution> configuration) {

        configuration.add(new DisplayBlockContribution("dateTime", "infra/AppPropertyDisplayBlocks", "dateTime"));
        configuration
                .add(new DisplayBlockContribution("dateMidnight", "infra/AppPropertyDisplayBlocks", "dateMidnight"));
        configuration.add(new DisplayBlockContribution("localDateTime", "infra/AppPropertyDisplayBlocks",
                "localDateTime"));
        configuration.add(new DisplayBlockContribution("localDate", "infra/AppPropertyDisplayBlocks", "localDate"));
        configuration.add(new DisplayBlockContribution("localTime", "infra/AppPropertyDisplayBlocks", "localTime"));

        configuration.add(new EditBlockContribution("dateMidnight", "infra/AppPropertyEditBlocks", "dateMidnight"));
        configuration.add(new EditBlockContribution("localDate", "infra/AppPropertyEditBlocks", "localDate"));

    }

}