Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * JBoss, Home of Professional Open Source.
   * Copyright 2014 Red Hat, Inc., and individual contributors
   * as indicated by the @author tags.
   *
   * Licensed under the Apache License, Version 2.0 (the "License");
   * you may not use this file except in compliance with the License.
   * You may obtain a copy of the License at
   *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  *  Unless required by applicable law or agreed to in writing, software
  *  distributed under the License is distributed on an "AS IS" BASIS,
  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  *  See the License for the specific language governing permissions and
  *  limitations under the License.
  */
 
 package io.undertow.server.handlers.cache;
 
 
 
 import static io.undertow.util.Methods.GET;
 import static io.undertow.util.Methods.HEAD;

Facade for an underlying buffer cache that contains response information.

This facade is attached to the exchange and provides a mechanism for handlers to serve cached content. By default a request to serve cached content is interpreted to mean that the resulting response is cacheable, and so by default this will result in the current response being cached (as long as it meets the criteria for caching).

Calling tryServeResponse can also result in the exchange being ended with a not modified response code, if the response headers indicate that this is justified (e.g. if the If-Modified-Since or If-None-Match headers indicate that the client has a cached copy of the response)

This should be installed early in the handler chain, before any content encoding handlers. This allows it to cache compressed copies of the response, which can significantly reduce CPU load.

NOTE: This cache has no concept of authentication, it assumes that if the underlying handler indicates that a response is cachable, then the current user has been properly authenticated to access that resource, and that the resource will not change per user.

Author(s):
Stuart Douglas
 
 public class ResponseCache {
 
     public static final AttachmentKey<ResponseCacheATTACHMENT_KEY = AttachmentKey.create(ResponseCache.class);
 
     private final DirectBufferCache cache;
     private final HttpServerExchange exchange;
     private boolean responseCachable;
 
     public ResponseCache(final DirectBufferCache cachefinal HttpServerExchange exchange) {
         this. = cache;
         this. = exchange;
     }

    
Attempts to serve the response from a cache.

If this fails, then the response will be considered cachable, and may be cached to be served by future handlers.

If this returns true then the caller should not modify the exchange any more, as this can result in a handoff to an IO thread

Returns:
true if serving succeeded,
 
     public boolean tryServeResponse() {
         return tryServeResponse(true);
     }

    
Attempts to serve the response from a cache.

If this fails, and the markCachable parameter is true then the response will be considered cachable, and may be cached to be served by future handlers.

If this returns true then the caller should not modify the exchange any more, as this can result in a handoff to an IO thread

Parameters:
markCacheable If this is true then the resulting response will be considered cachable
Returns:
true if serving succeeded,
    public boolean tryServeResponse(boolean markCacheable) {
        final CachedHttpRequest key = new CachedHttpRequest();
        DirectBufferCache.CacheEntry entry = .get(key);
        //we only cache get and head requests
        if (!.getRequestMethod().equals() &&
                !.getRequestMethod().equals()) {
            return false;
        }
        if (entry == null) {
            this. = markCacheable;
            return false;
        }
        // It's loading retry later
        if (!entry.enabled() || !entry.reference()) {
            this. = markCacheable;
            return false;
        }
        CachedHttpRequest existingKey = (CachedHttpRequestentry.key();
        //if any of the header matches fail we just return
        //we don't can the request, as it is possible the underlying handler
        //may have additional etags
        final ETag etag = existingKey.getEtag();
        if (!ETagUtils.handleIfMatch(etagfalse)) {
            return false;
        }
        //we do send a 304 if the if-none-match header matches
        if (!ETagUtils.handleIfNoneMatch(etagtrue)) {
            .setResponseCode(304);
            .endExchange();
            return true;
        }
        //the server may have a more up to date representation
        if (!DateUtils.handleIfUnmodifiedSince(existingKey.getLastModified())) {
            return false;
        }
        if (!DateUtils.handleIfModifiedSince(existingKey.getLastModified())) {
            .setResponseCode(304);
            .endExchange();
            return true;
        }
        //we are going to proceed. Set the appropriate headers
        if(existingKey.getContentType() != null) {
            .getResponseHeaders().put(.existingKey.getContentType());
        }
        if(existingKey.getContentEncoding() != null && !..equals(HttpString.tryFromString(existingKey.getContentEncoding()))) {
            .getResponseHeaders().put(.existingKey.getContentEncoding());
        }
        if(existingKey.getLastModified() != null) {
            .getResponseHeaders().put(., DateUtils.toDateString(existingKey.getLastModified()));
        }
        if(existingKey.getContentLocation() != null) {
            .getResponseHeaders().put(.existingKey.getContentLocation());
        }
        if(existingKey.getLanguage() != null) {
            .getResponseHeaders().put(.existingKey.getLanguage());
        }
        if(etag != null) {
            .getResponseHeaders().put(.etag.toString());
        }
        //TODO: support if-range
        if (.getRequestMethod().equals()) {
            .endExchange();
            return true;
        }
        final ByteBuffer[] buffers;
        boolean ok = false;
        try {
            LimitedBufferSlicePool.PooledByteBuffer[] pooled = entry.buffers();
            buffers = new ByteBuffer[pooled.length];
            for (int i = 0; i < buffers.lengthi++) {
                // Keep position from mutating
                buffers[i] = pooled[i].getResource().duplicate();
            }
            ok = true;
        } finally {
            if (!ok) {
                entry.dereference();
            }
        }
        // Transfer Inline, or register and continue transfer
        // Pass off the entry dereference call to the listener
        .getResponseSender().send(buffersnew DereferenceCallback(entry));
        return true;
    }
    boolean isResponseCachable() {
        return ;
    }
    private static class DereferenceCallback implements IoCallback {
        private final DirectBufferCache.CacheEntry cache;
        public DereferenceCallback(DirectBufferCache.CacheEntry cache) {
            this. = cache;
        }
        @Override
        public void onComplete(final HttpServerExchange exchangefinal Sender sender) {
            .dereference();
            exchange.endExchange();
        }
        @Override
        public void onException(final HttpServerExchange exchangefinal Sender senderfinal IOException exception) {
            ..ioException(exception);
            .dereference();
            exchange.endExchange();
        }
    }
New to GrepCode? Check out our FAQ X