package weaver.filter;
import com.engine.common.util.ParamUtil;
import weaver.general.BaseBean;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;


public class RequestLoggingFilter implements Filter {

    private BaseBean logger;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger = new BaseBean();
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            StringBuffer requestURI = ((HttpServletRequest) request).getRequestURL();
            // 获取请求方式
            String method = ((HttpServletRequest) request).getMethod();

            // 获取请求参数
                String queryString = ((HttpServletRequest) request).getQueryString();
            String remoteHost = request.getRemoteHost();
            Map parameterMap = request.getParameterMap();

            String userAgent = ((HttpServletRequest) request).getHeader("User-Agent");
            logger.writeLog("Request URL:-----" + requestURI);
            logger.writeLog("Request Method: " + method);
            logger.writeLog("Request Parameters: " + queryString);
            logger.writeLog("Request remoteHost: " + remoteHost);
            logger.writeLog("Request parameterMap: " + parameterMap.toString());
            logger.writeLog("Request userAgent: " + userAgent);
            chain.doFilter(request, response);
        }catch (Exception e){
            e.printStackTrace();
            logger.writeLog("RequestLoggingFilter: " + e.getMessage());
        }

    }

    @Override
    public void destroy() {

    }
}
