Permalink
Browse files

Introduced ResourceRoute's serveResource() and serveCacheableResource…

…() utility methods
  • Loading branch information...
fcamblor committed Jan 19, 2017
1 parent 34822ee commit 738968360b0315182dbc21825947905c19da4f08
Showing with 28 additions and 9 deletions.
  1. +28 −9 restx-core/src/main/java/restx/ResourcesRoute.java
@@ -14,6 +14,7 @@
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import static com.google.common.base.Preconditions.checkNotNull;
@@ -116,15 +117,7 @@ public void handle(RestxRequestMatch match, RestxRequest req, RestxResponse resp
|| RestxContext.Modes.TEST.equals(ctx.getMode())
|| RestxContext.Modes.INFINIREST.equals(ctx.getMode())
);
resp.setLogLevel(RestxLogLevel.QUIET);
resp.setStatus(HttpStatus.OK);
String contentType = HTTP.getContentTypeFromExtension(relativePath).or("application/octet-stream");
Optional<CachedResourcePolicy> cachedResourcePolicy = cachePolicyMatching(contentType, relativePath);
if(cachedResourcePolicy.isPresent()) {
resp.setHeader("Cache-Control", cachedResourcePolicy.get().getCacheValue());
}
resp.setContentType(contentType);
Resources.asByteSource(resource).copyTo(resp.getOutputStream());
serveCacheableResource(resp, resource, relativePath);
} catch (IllegalArgumentException e) {
notFound(resp, relativePath);
}
@@ -134,6 +127,32 @@ protected String requestRelativePath(RestxRequest req) {
return req.getRestxPath().substring(baseRestPath.length());
}
protected void serveCacheableResource(RestxResponse resp, URL resource, String relativePath) throws IOException {
String contentType = HTTP.getContentTypeFromExtension(relativePath).or("application/octet-stream");
ImmutableMap.Builder<String, String> headers = ImmutableMap.builder();
Optional<CachedResourcePolicy> cachedResourcePolicy = cachePolicyMatching(contentType, relativePath);
if(cachedResourcePolicy.isPresent()) {
headers.put("Cache-Control", cachedResourcePolicy.get().getCacheValue());
}
serveResource(resp, resource, contentType, headers.build());
}
protected void serveResource(RestxResponse resp, URL resource, String contentType) throws IOException {
serveResource(resp, resource, contentType, ImmutableMap.<String, String>of());
}
protected void serveResource(RestxResponse resp, URL resource, String contentType, Map<String, String> headers) throws IOException {
resp.setLogLevel(RestxLogLevel.QUIET);
resp.setStatus(HttpStatus.OK);
for(Map.Entry<String,String> headerEntry: headers.entrySet()) {
resp.setHeader(headerEntry.getKey(), headerEntry.getValue());
}
resp.setContentType(contentType);
Resources.asByteSource(resource).copyTo(resp.getOutputStream());
}
protected Optional<CachedResourcePolicy> cachePolicyMatching(String contentType, String path) {
for(CachedResourcePolicy cachedResourcePolicy : cachedResourcePolicies){
if(cachedResourcePolicy.matches(contentType, path)){

0 comments on commit 7389683

Please sign in to comment.