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.engine.encoders;
016
017import org.apache.tapestry.Tapestry;
018import org.apache.tapestry.asset.AssetService;
019import org.apache.tapestry.engine.ServiceEncoder;
020import org.apache.tapestry.engine.ServiceEncoding;
021import org.apache.tapestry.services.ServiceConstants;
022
023/**
024 * Encoder for the {@link org.apache.tapestry.asset.AssetService} that uses servlet path info
025 * to store the resource digest and the path to the resource.
026 * 
027 * @author Howard M. Lewis Ship
028 * @since 4.0
029 */
030public class AssetEncoder implements ServiceEncoder
031{
032    private String _path;
033
034    public void setPath(String path)
035    {
036        _path = path;
037    }
038
039    public void encode(ServiceEncoding encoding)
040    {
041        if (!encoding.getParameterValue(ServiceConstants.SERVICE).equals(Tapestry.ASSET_SERVICE))
042            return;
043
044        String path = encoding.getParameterValue(AssetService.PATH);
045        String digest = encoding.getParameterValue(AssetService.DIGEST);
046
047        // _path ends with a slash, path starts with one.
048
049        String fullPath = _path + "/" + digest + path;
050
051        encoding.setServletPath(fullPath);
052        encoding.setParameterValue(AssetService.PATH, null);
053        encoding.setParameterValue(AssetService.DIGEST, null);
054        encoding.setParameterValue(ServiceConstants.SERVICE, null);
055    }
056
057    public void decode(ServiceEncoding encoding)
058    {
059        if (!encoding.getServletPath().equals(_path))
060            return;
061
062        String pathInfo = encoding.getPathInfo();
063
064        // The lead character is a slash, so find the next slash (the divider between the
065        // digest and the path).
066        int slashx = pathInfo.indexOf('/', 1);
067
068        encoding.setParameterValue(ServiceConstants.SERVICE, Tapestry.ASSET_SERVICE);
069        encoding.setParameterValue(AssetService.DIGEST, pathInfo.substring(1, slashx));
070        encoding.setParameterValue(AssetService.PATH, pathInfo.substring(slashx));
071    }
072
073}