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