package com.unis.base.server.config;

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.nio.charset.Charset;


/**
 * @author zhanghonghuai
 *   
 *   HttpServletRequest包装类 每次返回都是一个新流，防止@Requestbody 读取不到数据
 */
public class BodyReaderHttpServletRequestWrapper extends HttpServletRequestWrapper {
	
    private final byte[] body;
    

    public BodyReaderHttpServletRequestWrapper(HttpServletRequest request) throws IOException {
        super(request);
        String bodyString = HttpHelper.getBodyString(request);
        
         //替换百分号，防止输入%查出所有数据
        if(bodyString!=null&&bodyString.length()>0) {
        	bodyString= bodyString.replaceAll("%", "--");
        }
        
        body = bodyString.getBytes(Charset.forName("UTF-8"));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);

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

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

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

            @Override
            public void setReadListener(ReadListener readListener) {
            }
        };
    }
    
    
    @Override
    public String getParameter(String name) {
    	
    	String parameter = super.getParameter(name);
    	
    	if(parameter!=null) {
    		
    		 parameter = parameter.replace("%", "--");
    	}
    	
    	return parameter;
    }
    
    
}

