package io.dropwizard.servlets;

import io.dropwizard.util.Duration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import static io.dropwizard.servlets.Servlets.getFullUrl;

/**
 * A servlet filter which logs the methods and URIs of requests which take longer than a given
 * duration of time to complete.
 */
@SuppressWarnings("UnusedDeclaration")
public class SlowRequestFilter implements Filter {
    private static final Logger LOGGER = LoggerFactory.getLogger(SlowRequestFilter.class);
    private final long threshold;

    /**
     * Creates a filter which logs requests which take longer than 1 second.
     */
    public SlowRequestFilter() {
        this(Duration.seconds(1));
    }

    /**
     * Creates a filter which logs requests which take longer than the given duration.
     *
     * @param threshold    the threshold for considering a request slow
     */
    public SlowRequestFilter(Duration threshold) {
        this.threshold = threshold.toNanoseconds();
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException { /* unused */ }

    @Override
    public void destroy() { /* unused */ }

    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        final HttpServletRequest req = (HttpServletRequest) request;
        final long startTime = System.nanoTime();
        try {
            chain.doFilter(request, response);
        } finally {
            final long elapsedMS = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime);
            if (elapsedMS >= threshold) {
                LOGGER.warn("Slow request: {} {} ({}ms)",
                            req.getMethod(),
                            getFullUrl(req), elapsedMS);
            }
        }
    }
}

@@ -141,17 +141,22 @@
 servlet.
-*
+Filter
 ;%0Aimport
@@ -170,16 +170,199 @@
 servlet.
+FilterChain;%0Aimport javax.servlet.FilterConfig;%0Aimport javax.servlet.ServletException;%0Aimport javax.servlet.ServletRequest;%0Aimport javax.servlet.ServletResponse;%0Aimport javax.servlet.
 http.Htt
@@ -408,46 +408,8 @@
 tion
-;%0Aimport java.util.concurrent.TimeUnit
 ;%0A%0Ai
@@ -464,16 +464,73 @@
 FullUrl;
+%0Aimport static java.util.concurrent.TimeUnit.NANOSECONDS;
 %0A%0A/**%0A *
@@ -1928,72 +1928,109 @@
 psed
-M
+N
 S = 
-TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime
+System.nanoTime() - startTime;%0A            final long elapsedMS = NANOSECONDS.toMillis(elapsedNS
 );%0A 
@@ -2051,17 +2051,17 @@
 (elapsed
-M
+N
 S %3E= thr

Fix comparison of elapsed time and threshold in SlowRequestFilter