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