content: /*
   *  Copyright (C) 2014 Stichting Akvo (Akvo Foundation)
   *
   *  This file is part of Akvo FLOW.
   *
   *  Akvo FLOW is free software: you can redistribute it and modify it under the terms of
   *  the GNU Affero General Public License (AGPL) as published by the Free Software Foundation,
   *  either version 3 of the License or any later version.
   *
   *  Akvo FLOW is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
   *  without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
   *  See the GNU Affero General Public License included below for more details.
   *
   *  The full license text can also be seen at <http://www.gnu.org/licenses/agpl.html>.
   */
  
  package com.gallatinsystems.framework.servlet;
  
  import java.io.BufferedReader;
  import java.io.ByteArrayInputStream;
  import java.io.ByteArrayOutputStream;
  import java.io.IOException;
  import java.io.InputStreamReader;
  
  import javax.servlet.ServletInputStream;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletRequestWrapper;
  
  import org.apache.commons.io.IOUtils;
  
  /**
   * HttpServletRequestWrapper that allows read more than once the request InputStream<br>
   * From: http://stackoverflow.com/a/17129256
   */
  
  public class MultiReadHttpServletRequest extends HttpServletRequestWrapper {
  
      private ByteArrayOutputStream cachedBytes;
  
      public MultiReadHttpServletRequest(HttpServletRequest request) {
          super(request);
      }
  
      @Override
      public ServletInputStream getInputStream() throws IOException {
          if (cachedBytes == null) {
              cacheInputStream();
          }
          return new CachedServletInputStream();
      }
  
      @Override
      public BufferedReader getReader() throws IOException {
          return new BufferedReader(new InputStreamReader(getInputStream()));
      }
  
      private void cacheInputStream() throws IOException {
          cachedBytes = new ByteArrayOutputStream();
          IOUtils.copy(super.getInputStream(), cachedBytes);
      }
  
      public class CachedServletInputStream extends ServletInputStream {
          private ByteArrayInputStream input;
  
          public CachedServletInputStream() {
              input = new ByteArrayInputStream(cachedBytes.toByteArray());
          }
  
          @Override
          public int read() throws IOException {
              return input.read();
          }
      }
  }
  