package com.nokia.tsl_data.util.logging.entity;

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

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

import org.springframework.util.StreamUtils;

/**
 * 可重复读取的HttpServletRequestWrapper
 */
public class RepeatableHttpServletRequestWrapper extends HttpServletRequestWrapper {
    // 承载request中的数据，以便重复读取
    private final byte[] bytes;

    public RepeatableHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        // 读取request中的数据到bytes
        bytes = StreamUtils.copyToByteArray(request.getInputStream());
    }

    @Override
    public ServletInputStream getInputStream() {
        ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
        // 匿名内部类实现ServletInputStream
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return stream.available() <= 0;
            }

            @Override
            public boolean isReady() {
                return stream.available() > 0;
            }

            @Override
            public void setReadListener(ReadListener readListener) {
                try {
                    readListener.onDataAvailable();
                    if (isFinished()) {
                        readListener.onAllDataRead();
                    }
                } catch (IOException e) {
                    readListener.onError(e);
                }
            }

            @Override
            public int read() {
                return stream.read();
            }
        };
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream(), getCharacterEncoding()));
    }
}
