package com.beagle.base.common.filter;

import java.io.IOException;
import java.util.UUID;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;

import org.slf4j.MDC;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;

/**
 * @author wuwanli
 */
public class LogbackFilter implements Filter {

    private static final String TRACE_ID = "traceId";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
            throws IOException, ServletException {
        boolean result = this.insertMdc();
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            if (result) {
                MDC.remove(TRACE_ID);
            }
        }
    }

    private boolean insertMdc() {
        try {
            MDC.put(TRACE_ID, UUID.randomUUID().toString().replace("-", ""));
            return true;
        } catch (Exception exception) {
            return false;
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
