package com.bonus.common.security.interceptor;


import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

/**
 * 包装和增强原始的 HttpServletRequest 对象，允许多次读取请求体（body）的数据，特别是在处理请求时使用流读取数据的情况下
 * @author 黑子
 */
public class ReadHttpRequestWrapper extends HttpServletRequestWrapper {

    private final String body;

    private final Map<String, String[]> parameters;

    /**
     *
     * @param request
     */
    public ReadHttpRequestWrapper(HttpServletRequest request,Map<String, String[]> parameters) throws IOException {
        super(request);
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = request.getReader();
        String readCount = "";
        while((readCount = reader.readLine()) != null){
            sb.append(readCount);
        }
        this.parameters = parameters;
        body = sb.toString();
    }

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

    @Override
    public ServletInputStream getInputStream() {
        final ByteArrayInputStream byteArrayIns = new ByteArrayInputStream(body.getBytes());
        ServletInputStream servletIns = new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

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

            @Override
            public void setReadListener(javax.servlet.ReadListener listener) {

            }

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