001// Copyright 2010, 2011 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.services.templates;
016
017import org.apache.tapestry5.TapestryConstants;
018import org.apache.tapestry5.ioc.Resource;
019import org.apache.tapestry5.ioc.internal.util.InternalUtils;
020import org.apache.tapestry5.model.ComponentModel;
021import org.apache.tapestry5.services.ComponentClassResolver;
022import org.apache.tapestry5.services.templates.ComponentTemplateLocator;
023
024import java.util.Locale;
025
026/**
027 * The special case for pages, where the template is searched for in the web application context.
028 *
029 * @since 5.2.0
030 */
031public class PageTemplateLocator implements ComponentTemplateLocator
032{
033    private final Resource contextRoot;
034
035    private final ComponentClassResolver resolver;
036
037    private final String prefix;
038
039    public PageTemplateLocator(Resource contextRoot, ComponentClassResolver resolver, String applicationFolder)
040    {
041        this.contextRoot = contextRoot;
042        this.resolver = resolver;
043
044        prefix = applicationFolder.equals("") ? "" : applicationFolder + "/";
045    }
046
047    public Resource locateTemplate(ComponentModel model, Locale locale)
048    {
049        if (!model.isPage())
050        {
051            return null;
052        }
053
054        String className = model.getComponentClassName();
055
056        String logicalName = resolver.resolvePageClassNameToPageName(className);
057
058        int slashx = logicalName.lastIndexOf('/');
059
060        if (slashx > 0)
061        {
062            // However, the logical name isn't quite what we want. It may have been somewhat
063            // trimmed.
064
065            String simpleClassName = InternalUtils.lastTerm(className);
066
067            logicalName = logicalName.substring(0, slashx + 1) + simpleClassName;
068        }
069
070        String path = prefix + logicalName + "." + TapestryConstants.TEMPLATE_EXTENSION;
071
072        return contextRoot.forFile(path).forLocale(locale);
073    }
074
075}