package com.atlassian.stash.internal.johnson.filters;

import com.atlassian.johnson.filters.Johnson503Filter;
import com.atlassian.stash.internal.johnson.JohnsonBypassHelper;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * Extends the {@link Johnson503Filter} to add {@link JohnsonBypassHelper#isBypassed(ServletRequest) bypass} support.
 *
 * @since 2.1
 * @see JohnsonBypassHelper
 */
public class BypassableJohnson503Filter extends Johnson503Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        if (JohnsonBypassHelper.isBypassed(request)) {
            //Johnson processing for this filter should be bypassed. Either there are no active events or the correct
            //token was supplied to bypass them.
            filterChain.doFilter(request, response);
        } else {
            //If we make it here, either a token was not supplied, the wrong token was supplied, no maintenance is in
            //progress or more Johnson events exist than just maintenance (indicating the system is more deeply locked)
            super.doFilter(request, response, filterChain);
        }
    }
}