001// Licensed under the Apache License, Version 2.0 (the "License");
002// you may not use this file except in compliance with the License.
003// You may obtain a copy of the License at
004//
005// http://www.apache.org/licenses/LICENSE-2.0
006//
007// Unless required by applicable law or agreed to in writing, software
008// distributed under the License is distributed on an "AS IS" BASIS,
009// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
010// See the License for the specific language governing permissions and
011// limitations under the License.
012
013package org.apache.tapestry5.internal.services.assets;
014
015import org.apache.tapestry5.services.assets.AssetChecksumGenerator;
016import org.apache.tapestry5.services.assets.CompressionStatus;
017import org.apache.tapestry5.services.assets.StreamableResource;
018
019import java.io.BufferedOutputStream;
020import java.io.ByteArrayOutputStream;
021import java.io.IOException;
022import java.io.OutputStream;
023import java.util.zip.GZIPOutputStream;
024
025/**
026 * GZip compressed representation of a {@link StreamableResource}.
027 *
028 * @since 5.4
029 */
030public class CompressedStreamableResource extends StreamableResourceImpl
031{
032    public CompressedStreamableResource(StreamableResource base, AssetChecksumGenerator assetChecksumGenerator) throws IOException
033    {
034        super(base.getDescription(), base.getContentType(), CompressionStatus.COMPRESSED, base.getLastModified(), compressContent(base), assetChecksumGenerator, base.getResponseCustomizer());
035
036        assert base.getCompression() == CompressionStatus.COMPRESSABLE;
037    }
038
039    private static BytestreamCache compressContent(StreamableResource resource) throws IOException
040    {
041        ByteArrayOutputStream compressed = new ByteArrayOutputStream(resource.getSize());
042        OutputStream compressor = new BufferedOutputStream(new GZIPOutputStream(compressed));
043
044        resource.streamTo(compressor);
045
046        compressor.close();
047
048        return new BytestreamCache(compressed);
049    }
050}