title: Reading ServletOutputStream to String
body: <p>I am trying to read the result of FreemarkerView rendering:</p>
  
  <pre><code>View view = viewResolver.resolveViewName(viewName, locale);
  view.render(model, request, mockResponse);
  </code></pre>
  
  <p>To read the result, I have created <code>mockResponse</code>, which encapsulates the HttpServletResponse:</p>
  
  <pre><code>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"));
      }
  }
  </code></pre>
  
  <p>And also my ServletOutputStream, which builds the String using StringBuilder:</p>
  
  <pre><code>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();
      }
  }
  </code></pre>
  
  <p>With those I am able to easily read the response with method <code>ServletOutputStreamEx.toString</code>.</p>
  
  <p>My problem is that the write method is not called in correct order and in the end the final String is <strong>mixed and not in correct order</strong>. This is probably caused by concurrency in Freemarker, but I have no idea how to fix it.</p>