package com.oqpo.api.web.filter;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

public class HttpRequestWrapper extends HttpServletRequestWrapper {
	private byte[] bodyData;

	public HttpRequestWrapper(HttpServletRequest request) throws IOException {
		super(request);
		InputStream is = super.getInputStream();
		bodyData = IOUtils.toByteArray(is);
	}

	@Override
	public ServletInputStream getInputStream() throws IOException {
		final ByteArrayInputStream bis = new ByteArrayInputStream(bodyData);
		return new ServletInputStreamImpl(bis);
	}
}

class ServletInputStreamImpl extends ServletInputStream {
	private InputStream is;

	public ServletInputStreamImpl(InputStream bis) {
		is = bis;
	}

	@Override
	public int read() throws IOException {
		return is.read();
	}

	@Override
	public int read(byte[] b) throws IOException {
		return is.read(b);
	}

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

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

	@Override
	public void setReadListener(ReadListener rl) {
		throw new RuntimeException("Not implemented");
	}
}
