com.pagecrumb.proxy.wrapper.RewriteServletOutputStream.java Source code

Java tutorial

Introduction

Here is the source code for com.pagecrumb.proxy.wrapper.RewriteServletOutputStream.java

Source

/**
 *    
 * Copyright 2013 Pagecrumb
 *
 * 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.pagecrumb.proxy.wrapper;

import java.io.IOException;
import java.io.OutputStream;
import java.nio.channels.Channels;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletOutputStream;

import org.apache.commons.io.output.ProxyOutputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.htmlparser.util.ParserException;

public class RewriteServletOutputStream extends ServletOutputStream {

    protected final Log log = LogFactory.getLog(getClass());

    private StringBuilder sb = new StringBuilder();

    private final OutputStream stream;

    public RewriteServletOutputStream(OutputStream stream) {
        this.stream = stream;
    }

    @Override
    public void write(int b) throws IOException {
        sb.append((char) b);
        //this.stream.write(b);
    }

    public void flush() throws IOException {
        super.flush();
        this.stream.flush();
    }

    public void close() throws IOException {
        //for (int i=0;i<sb.toString().length();i++) {
        //   char c = sb.toString().charAt(i);
        //   this.stream.write(c);
        //}

        try {
            HtmlProxyTransformWrapper wrapper = new HtmlProxyTransformWrapper(sb.toString());
            //Write to target output stream.
            for (int i = 0; i < wrapper.getHTML().length(); i++) {
                char c = wrapper.getHTML().charAt(i);
                this.stream.write(c);
            }
        } catch (ParserException e) {
            log.error("Caught parser exception - " + e);
        }

        sb.setLength(0); // Clear string buffer
        super.close();
        this.stream.close();
    }

}