package com.eactive.eai.adapter.controller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class CachedBodyHttpServletRequest extends HttpServletRequestWrapper {

	 private final byte[] cachedBody;

	    public CachedBodyHttpServletRequest(HttpServletRequest request, byte[] body) {
	        super(request);
	        this.cachedBody = body;
	    }

	    @Override
	    public ServletInputStream getInputStream() {
	        ByteArrayInputStream bais = new ByteArrayInputStream(cachedBody);

	        return new ServletInputStream() {
	            @Override
	            public int read() {
	                return bais.read();
	            }

	            @Override
	            public boolean isFinished() {
	                return bais.available() == 0;
	            }

	            @Override
	            public boolean isReady() {
	                return true;
	            }

	            @Override
	            public void setReadListener(ReadListener readListener) {
	            }
	        };
	    }

	    @Override
	    public BufferedReader getReader() {
	        return new BufferedReader(new InputStreamReader(getInputStream()));
	    }
	}
