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