001 // Copyright 2004, 2005 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
015 package org.apache.tapestry.web;
016
017 import java.util.Locale;
018
019 import org.apache.hivemind.util.LocalizedNameGenerator;
020 import org.apache.hivemind.util.LocalizedResource;
021
022 /**
023 * Finds localized resources within a {@link org.apache.tapestry.web.WebContext}..
024 *
025 * @author Howard Lewis Ship
026 * @since 4.0
027 */
028
029 public class LocalizedWebContextResourceFinder
030 {
031 private WebContext _context;
032
033 public LocalizedWebContextResourceFinder(WebContext context)
034 {
035 _context = context;
036 }
037
038 /**
039 * Resolves the resource, returning a path representing the closest match (with respect to the
040 * provided locale). Returns null if no match.
041 * <p>
042 * The provided path is split into a base path and a suffix (at the last period character). The
043 * locale will provide different suffixes to the base path and the first match is returned.
044 */
045
046 public LocalizedResource resolve(String contextPath, Locale locale)
047 {
048 int dotx = contextPath.lastIndexOf('.');
049 String basePath;
050 String suffix;
051 if (dotx >= 0) {
052 basePath = contextPath.substring(0, dotx);
053 suffix = contextPath.substring(dotx);
054 }
055 else
056 {
057 // Resource without extension
058 basePath = contextPath;
059 suffix = "";
060 }
061
062 LocalizedNameGenerator generator = new LocalizedNameGenerator(basePath, locale, suffix);
063
064 while (generator.more())
065 {
066 String candidatePath = generator.next();
067
068 if (isExistingResource(candidatePath))
069 return new LocalizedResource(candidatePath, generator.getCurrentLocale());
070 }
071
072 return null;
073 }
074
075 private boolean isExistingResource(String path)
076 {
077 return _context.getResource(path) != null;
078 }
079 }