package info.aspirecn.iov.sjjh.servicenode.fed.filter;


import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author jianggang
 * @Date 2018/11/21 15:33:10
 * @Description
 */

@Slf4j
public class VueIndexFilter implements Filter {

    private String noforward = "assets;css;fonts;img;js;api";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)servletRequest;
        String uri = request.getRequestURI();
        if(isForward(uri)){
            log.info("------->转发的uri{}",uri);
            servletRequest.getRequestDispatcher("/").forward(servletRequest,servletResponse);
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }


    private boolean isForward(String uri){
        String targetUri = uri.substring(0,uri.lastIndexOf('/'));
        int temp = 0;
        String finalStr = "";
        if(targetUri.lastIndexOf('/')>0){
            temp = targetUri.lastIndexOf('/')+1;
            finalStr = uri.substring(temp,uri.lastIndexOf('/'));
        }else{
            finalStr = uri.substring(temp,uri.lastIndexOf('/'));
           if(finalStr.length()>0){
               finalStr = uri.substring(1,uri.lastIndexOf('/'));
           }
        }
        String[] strs = noforward.split(";");
        for(String str : strs){
            if(finalStr.equals(str)){
                return false;
            }
        }
        return true;
    }
}
