com.bennavetta.appsite.postprocessor.CssMinifier.java Source code

Java tutorial

Introduction

Here is the source code for com.bennavetta.appsite.postprocessor.CssMinifier.java

Source

/**
 * Copyright 2013 Ben Navetta <ben@bennavetta.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bennavetta.appsite.postprocessor;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;

import ro.isdc.wro.model.resource.Resource;
import ro.isdc.wro.model.resource.ResourceType;
import ro.isdc.wro.model.resource.processor.impl.css.CssCompressorProcessor;

import com.bennavetta.appsite.processing.OutputProcessor;
import com.bennavetta.appsite.processing.Request;
import com.bennavetta.appsite.processing.Response;
import com.google.common.base.Charsets;
import com.google.common.net.MediaType;

public class CssMinifier implements OutputProcessor {
    private CssCompressorProcessor processor = new CssCompressorProcessor();

    @Override
    public void postProcess(InputStream in, OutputStream out, Request request, Response response)
            throws IOException {
        Charset inEncoding = request.getCharacterEncoding() != null ? request.getCharacterEncoding()
                : Charsets.UTF_8;
        response.setCharacterEncoding(Charsets.UTF_8);
        response.setContentType(MediaType.CSS_UTF_8);
        Reader inReader = new InputStreamReader(in, inEncoding);
        Writer outWriter = new OutputStreamWriter(out, Charsets.UTF_8);
        processor.process(Resource.create(request.getURI(), ResourceType.CSS), inReader, outWriter);
    }

    @Override
    public boolean canPostProcess(String path, Request request, Response response) {
        if (path.endsWith(".css"))
            return true;
        if (response.getContentType() != null
                && response.getContentType().withoutParameters().equals(MediaType.CSS_UTF_8))
            return true;
        return false;
    }

}