Wrapping an entire request with before/after

52 views
Skip to first unread message

Zack Sampson

unread,
Dec 16, 2020, 7:16:49 PM12/16/20
to dropwizard-user
Hey all,

I've wondered how to do this for years and have never quite managed to figure it out. For the purpose of metrics, I'd like to wrap a request such that I get the chance to, say, increment a counter while it runs, and then decrement it after it completes. Unlike a ContainerResponseFilter, I don't want to decrement until the body completes, if there is one.

Is there a better way to do this than by frankensteining together an interceptor and request filters?

Thank you!
Zack

Jochen Schalanda

unread,
Dec 18, 2020, 2:45:50 AM12/18/20
to dropwizard-user
Hi Zack,

you could write a Handler for Jetty, similar to the one used in Dropwizard/Dropwizard Metrics [1] to get the metrics you want.


Best regards,
Jochen

Shawn Smith

unread,
Dec 18, 2020, 1:18:28 PM12/18/20
to dropwiz...@googlegroups.com
Alternatively, if you want to do this within Jersey and have access to all the request metadata available to a Jersey ContainerRequestFilter, you can inject Jersey's CloseableService and register a callback that will be invoked after the body completes. The callback will be invoked whether or not the request succeeds.

Here's a mockup:
import org.glassfish.jersey.server.CloseableService;

import javax.inject.Inject;
import javax.inject.Singleton;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.core.Context;
import java.io.Closeable;

@Singleton
public class TrackingFilter implements ContainerRequestFilter {
private final CloseableService closer;

@Inject
public TrackingFilter(@Context CloseableService closer) {
this.closer = closer;
}

@Override
public void filter(ContainerRequestContext requestContext) {
closer.add(startTracking(requestContext));
}

private Closeable startTracking(ContainerRequestContext requestContext) {
String requestPath = requestContext.getUriInfo().getPath();
long start = System.nanoTime();
return () -> {
long stop = System.nanoTime();
System.out.println("elapsed=" + (stop - start) + " nanos, request path=" + requestPath);
};
}
}

--
You received this message because you are subscribed to the Google Groups "dropwizard-user" group.
To unsubscribe from this group and stop receiving emails from it, send an email to dropwizard-us...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/dropwizard-user/F21A5388-4DCD-42E2-A820-E9165EC4B3AE%40schalanda.name.
Reply all
Reply to author
Forward
0 new messages