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