|
| 1 | +package com.graphhopper.converter.api; |
| 2 | + |
| 3 | +import com.google.common.cache.Cache; |
| 4 | +import com.google.common.cache.CacheBuilder; |
| 5 | + |
| 6 | +import javax.ws.rs.container.ContainerRequestContext; |
| 7 | +import javax.ws.rs.container.ContainerResponseContext; |
| 8 | +import javax.ws.rs.container.ContainerResponseFilter; |
| 9 | +import javax.ws.rs.container.PreMatching; |
| 10 | +import javax.ws.rs.core.Response; |
| 11 | +import javax.ws.rs.ext.Provider; |
| 12 | +import java.io.IOException; |
| 13 | +import java.util.concurrent.TimeUnit; |
| 14 | + |
| 15 | +@Provider |
| 16 | +@PreMatching |
| 17 | +public class CacheFilter implements ContainerResponseFilter { |
| 18 | + |
| 19 | + private static final Cache<String, Response> cache = CacheBuilder.newBuilder() |
| 20 | + .maximumSize(1000) |
| 21 | + .expireAfterWrite(10, TimeUnit.MINUTES) |
| 22 | + .build(); |
| 23 | + |
| 24 | + @Override |
| 25 | + public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) throws IOException { |
| 26 | + if (!"GET".equalsIgnoreCase(requestContext.getMethod())) { |
| 27 | + return; // Only cache GET requests |
| 28 | + } |
| 29 | + |
| 30 | + // TODO headers are ignored. shouldn't be a problem |
| 31 | + |
| 32 | + String requestKey = requestContext.getUriInfo().getRequestUri().toString(); |
| 33 | + Response cachedResponse = cache.getIfPresent(requestKey); |
| 34 | + if (cachedResponse != null) { |
| 35 | + // LoggerFactory.getLogger(getClass()).info("now accessing cache"); |
| 36 | + responseContext.setStatus(cachedResponse.getStatus()); |
| 37 | + responseContext.setEntity(cachedResponse.getEntity()); |
| 38 | + return; |
| 39 | + } |
| 40 | + |
| 41 | + cache.put(requestKey, Response.status(responseContext.getStatus()) |
| 42 | + .entity(responseContext.getEntity()) |
| 43 | + .build()); |
| 44 | + } |
| 45 | +} |
0 commit comments