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
015package org.apache.hivemind.util;
016
017import java.net.URL;
018import java.util.Locale;
019
020import org.apache.hivemind.ClassResolver;
021import org.apache.hivemind.Resource;
022
023/**
024 * Implementation of {@link org.apache.hivemind.Resource}
025 * for resources found within the classpath.
026 * 
027 *
028 * @author Howard Lewis Ship
029 */
030
031public class ClasspathResource extends AbstractResource
032{
033    private ClassResolver _resolver;
034
035    public ClasspathResource(ClassResolver resolver, String path)
036    {
037        this(resolver, path, null);
038    }
039
040    public ClasspathResource(ClassResolver resolver, String path, Locale locale)
041    {
042        super(path, locale);
043
044        _resolver = resolver;
045    }
046
047    /**
048     * Locates the localization of the
049     * resource using {@link LocalizedResourceFinder}. 
050     */
051
052    public Resource getLocalization(Locale locale)
053    {
054        String path = getPath();
055        LocalizedResourceFinder finder = new LocalizedResourceFinder(_resolver);
056
057        LocalizedResource localizedResource = finder.resolve(path, locale);
058
059        if (localizedResource == null)
060            return null;
061
062        String localizedPath = localizedResource.getResourcePath();
063        Locale pathLocale = localizedResource.getResourceLocale();
064
065        if (localizedPath == null)
066            return null;
067
068        if (path.equals(localizedPath))
069            return this;
070
071        return new ClasspathResource(_resolver, localizedPath, pathLocale);
072    }
073
074    /**
075     * Invokes {@link ClassResolver#getResource(String)} with the path.
076     */
077
078    public URL getResourceURL()
079    {
080        return _resolver.getResource(getPath());
081    }
082
083    public String toString()
084    {
085        return "classpath:" + getPath();
086    }
087
088    public int hashCode()
089    {
090        return 4783 & getPath().hashCode();
091    }
092
093    protected Resource newResource(String path)
094    {
095        return new ClasspathResource(_resolver, path);
096    }
097
098}