001// Copyright 2013 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.tapestry5.internal.services.assets;
016
017import org.apache.tapestry5.internal.services.ResourceStreamer;
018import org.apache.tapestry5.ioc.Resource;
019
020import java.io.IOException;
021
022/**
023 * Utility used by {@link org.apache.tapestry5.services.assets.AssetRequestHandler} implementations
024 * where the first folder in the extra path is actually a computed checksum of the resource's content.
025 *
026 * @since 5.4
027 */
028public class ChecksumPath
029{
030    public final String checksum;
031
032    public final String resourcePath;
033
034    private final ResourceStreamer streamer;
035
036    public ChecksumPath(ResourceStreamer streamer, String baseFolder, String extraPath)
037    {
038        this.streamer = streamer;
039        int slashx = extraPath.indexOf('/');
040
041        checksum = extraPath.substring(0, slashx);
042
043        String morePath = extraPath.substring(slashx + 1);
044
045        resourcePath = baseFolder == null
046                ? morePath
047                : baseFolder + "/" + morePath;
048    }
049
050    /**
051     * If the resource exists and the checksum is correct, stream it to the client and return true. Otherwise,
052     * return false.
053     *
054     * @param resource
055     *         to stream
056     * @return true if streamed, false otherwise
057     * @throws IOException
058     */
059    public boolean stream(Resource resource) throws IOException
060    {
061        if (resource == null || !resource.exists())
062        {
063            return false;
064        }
065
066
067        return streamer.streamResource(resource, checksum, ResourceStreamer.DEFAULT_OPTIONS);
068    }
069}