package com.xingxi.api.configuration;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StreamUtils;

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;

class ContentCachingRequestWrapper extends HttpServletRequestWrapper {
    private byte[] cachedContent;

    public ContentCachingRequestWrapper(HttpServletRequest request) {
        super(request);
    }

    private byte[] getCachedContent() throws IOException {
        if (ObjectUtils.isEmpty(cachedContent)) {
            cachedContent = StreamUtils.copyToByteArray(getRequest().getInputStream());
        }
        return cachedContent;
    }

    public byte[] getContentAsByteArray() {
        return cachedContent;
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(getCachedContent());
        return new ServletInputStream() {

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

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

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

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

}
