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.templates;
014
015import org.apache.tapestry5.TapestryConstants;
016import org.apache.tapestry5.commons.Resource;
017import org.apache.tapestry5.ioc.internal.util.InternalUtils;
018import org.apache.tapestry5.model.ComponentModel;
019import org.apache.tapestry5.services.ComponentClassResolver;
020import org.apache.tapestry5.services.templates.ComponentTemplateLocator;
021
022import java.util.Locale;
023
024/**
025 * The special case for pages, where the template is searched for in the web application context.
026 *
027 * @since 5.2.0
028 */
029public class PageTemplateLocator implements ComponentTemplateLocator
030{
031    private final Resource contextRoot;
032
033    private final ComponentClassResolver resolver;
034
035    private final String prefix;
036
037    public PageTemplateLocator(Resource contextRoot, ComponentClassResolver resolver, String applicationFolder)
038    {
039        this.contextRoot = contextRoot;
040        this.resolver = resolver;
041
042        prefix = applicationFolder.equals("") ? "" : applicationFolder + "/";
043    }
044
045    public Resource locateTemplate(ComponentModel model, Locale locale)
046    {
047        if (!model.isPage())
048        {
049            return null;
050        }
051
052        String className = model.getComponentClassName();
053
054        String logicalName = resolver.resolvePageClassNameToPageName(className);
055
056        String simpleClassName = InternalUtils.lastTerm(className);
057
058        int slashx = logicalName.lastIndexOf('/');
059
060        // Using the simple class name always accounts for the case where a "page" suffix was stripped off to form
061        // the logical page name (and several other cases where the name was simplified in some way).
062        String baseName = slashx < 0 ? simpleClassName : logicalName.substring(0, slashx + 1) + simpleClassName;
063
064        String path = prefix + baseName + "." + TapestryConstants.TEMPLATE_EXTENSION;
065
066        return contextRoot.forFile(path).forLocale(locale);
067    }
068
069}