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.util.Locale;
018    
019    import org.apache.hivemind.ClassResolver;
020    
021    /**
022     * Searches for a localization of a
023     * particular resource in the classpath (using
024     * a {@link org.apache.hivemind.ClassResolver}. 
025     * 
026     *
027     * @author Howard Lewis Ship
028     */
029    public class LocalizedResourceFinder
030    {
031        private ClassResolver _resolver;
032    
033        public LocalizedResourceFinder(ClassResolver resolver)
034        {
035            _resolver = resolver;
036        }
037    
038        /**
039         * Resolves the resource, returning a path representing
040         * the closest match (with respect to the provided locale).
041         * Returns null if no match.
042         * 
043         * <p>The provided path is split into a base path
044         * and a suffix (at the last period character).  The locale
045         * will provide different suffixes to the base path
046         * and the first match is returned. 
047         */
048        
049        public LocalizedResource resolve(String resourcePath, Locale locale)
050        {
051            int dotx = resourcePath.lastIndexOf('.');
052            String basePath;
053            String suffix;
054            if (dotx >= 0) {
055                    basePath = resourcePath.substring(0, dotx);
056                    suffix = resourcePath.substring(dotx);
057            }
058            else
059            {
060                    // Resource without extension
061                    basePath = resourcePath;
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 (_resolver.getResource(candidatePath) != null)
072                    return new LocalizedResource(candidatePath, generator.getCurrentLocale());
073            }
074    
075            return null;
076        }
077    }