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.webresources;
016
017import com.yahoo.platform.yui.compressor.CssCompressor;
018import org.apache.commons.io.IOUtils;
019import org.apache.tapestry5.ioc.OperationTracker;
020import org.apache.tapestry5.ioc.internal.util.InternalUtils;
021import org.apache.tapestry5.services.assets.AssetChecksumGenerator;
022import org.apache.tapestry5.services.assets.StreamableResource;
023import org.slf4j.Logger;
024
025import java.io.*;
026
027/**
028 * A wrapper around YUI Compressor. This module does not have a dependency on YUICompressor;
029 * isntead a local copy of the YUICompressor CSS minimizer is kept (because the reset of YUICompressor
030 * is painful to mix due to how it attempts to patch Rhino).
031 */
032public class CSSMinimizer extends AbstractMinimizer
033{
034    public CSSMinimizer(Logger logger, OperationTracker tracker, AssetChecksumGenerator checksumGenerator)
035    {
036        super(logger, tracker, checksumGenerator, "text/css");
037    }
038
039    @Override
040    protected InputStream doMinimize(StreamableResource resource) throws IOException
041    {
042        StringWriter writer = new StringWriter(1000);
043        Reader reader = new InputStreamReader(resource.openStream());
044
045        try
046        {
047            new CssCompressor(reader).compress(writer, -1);
048
049            writer.flush();
050
051            return IOUtils.toInputStream(writer.getBuffer());
052        } finally
053        {
054            InternalUtils.close(reader);
055            InternalUtils.close(writer);
056        }
057    }
058}