//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package com.chushang.common.feign.filter;

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

import com.alibaba.fastjson2.JSONObject;
import com.chushang.common.core.constant.CommonConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

public class MdcFilter implements Filter {
    private static final Logger log = LoggerFactory.getLogger(MdcFilter.class);

    public MdcFilter() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest)request;
        String trace = req.getHeader(CommonConstants.TRACE_ID);
        String span = req.getHeader(CommonConstants.SPAN);
        String uri = req.getRequestURI();
        String userAgent = req.getHeader("user-agent");
        if (!uri.contains(".") || userAgent.startsWith("Java")) {
            MDC.put(CommonConstants.TRACE_ID, Objects.requireNonNullElseGet(trace, () -> UUID.randomUUID().toString().replaceAll("-", "")));
            MDC.put(CommonConstants.SPAN, Objects.requireNonNullElseGet(span, () -> UUID.randomUUID().toString().replaceAll("-", "")));
        }

        chain.doFilter(request, response);
        MDC.clear();
    }
}
