Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading ServletOutputStream to String

I am trying to read the result of FreemarkerView rendering:

View view = viewResolver.resolveViewName(viewName, locale);
view.render(model, request, mockResponse);

To read the result, I have created mockResponse, which encapsulates the HttpServletResponse:

public class HttpServletResponseEx extends HttpServletResponseWrapper {

    ServletOutputStream outputStream;

    public HttpServletResponseEx(HttpServletResponse response) throws IOException {
        super(response);
        outputStream = new ServletOutputStreamEx();
    }

    @Override
    public ServletOutputStream getOutputStream() {
        return outputStream;
    }

    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"));
    }
}

And also my ServletOutputStream, which builds the String using StringBuilder:

public class ServletOutputStreamEx extends ServletOutputStream {

    StringBuilder stringBuilder;

    public ServletOutputStreamEx() {
        this.stringBuilder = new StringBuilder();
    }

    @Override
    public void write(int b) throws IOException {
    } 

    @Override
    public void write(byte b[], int off, int len) throws IOException {
        stringBuilder.append(new String(b, "UTF-8"));
    }

    @Override
    public String toString() {
        return stringBuilder.toString();
    }
}

With those I am able to easily read the response with method ServletOutputStreamEx.toString.

My problem is that the write method is not called in correct order and in the end the final String is mixed and not in correct order. This is probably caused by concurrency in Freemarker, but I have no idea how to fix it.

like image 236
Vojtěch Avatar asked Mar 11 '12 15:03

Vojtěch


1 Answers

Thanks for the responses: the write(int b) was not implemented, because it is never called. The problem in the end is the byte array, which also contains the previous String. So the String needs to be created as String(b, off, len, "UTF-8").

like image 98
Vojtěch Avatar answered Oct 03 '22 08:10

Vojtěch