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

Java tutorial

Introduction

Here is the source code for com.bennavetta.appsite.postprocessor.SourcePostProcessor.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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.io.CharStreams;
import com.google.common.net.MediaType;
import com.ibm.icu.text.CharsetDetector;

public class SourcePostProcessor implements OutputProcessor {
    private Logger log = LoggerFactory.getLogger(getClass());
    private CharsetDetector detector = new CharsetDetector();

    @Override
    public void postProcess(InputStream inStream, OutputStream outStream, Request request, Response response)
            throws IOException {
        log.debug("Processing {}", request.getURI());
        response.setContentType(MediaType.HTML_UTF_8);
        response.setCharacterEncoding(Charsets.UTF_8);
        Writer out = new OutputStreamWriter(outStream, Charsets.UTF_8);
        out.write("<html><head><title>");
        out.write(request.getURI());
        out.write("</title></head></body><pre>");
        Reader in = detector.getReader(inStream, Charsets.UTF_8.name());
        if (in == null) {
            in = new InputStreamReader(inStream, Charsets.UTF_8);
        }
        CharStreams.copy(in, out);
        out.write("</pre></body></html>");
        out.flush();
    }

    @Override
    public boolean canPostProcess(String path, Request request, Response response) {
        return path.endsWith(".src");
    }

}