Search in sources :

Example 1 with ResponseCachingSender

use of io.undertow.server.handlers.cache.ResponseCachingSender in project undertow by undertow-io.

the class CachedResource method serve.

@Override
public void serve(final Sender sender, final HttpServerExchange exchange, final IoCallback completionCallback) {
    final DirectBufferCache dataCache = cachingResourceManager.getDataCache();
    if (dataCache == null) {
        underlyingResource.serve(sender, exchange, completionCallback);
        return;
    }
    final DirectBufferCache.CacheEntry existing = dataCache.get(cacheKey);
    final Long length = getContentLength();
    // if it is not eligible to be served from the cache
    if (length == null || length > cachingResourceManager.getMaxFileSize()) {
        underlyingResource.serve(sender, exchange, completionCallback);
        return;
    }
    // it is not cached yet, install a wrapper to grab the data
    if (existing == null || !existing.enabled() || !existing.reference()) {
        Sender newSender = sender;
        final DirectBufferCache.CacheEntry entry;
        if (existing == null) {
            entry = dataCache.add(cacheKey, length.intValue(), cachingResourceManager.getMaxAge());
        } else {
            entry = existing;
        }
        if (entry != null && entry.buffers().length != 0 && entry.claimEnable()) {
            if (entry.reference()) {
                newSender = new ResponseCachingSender(sender, entry, length);
            } else {
                entry.disable();
            }
        }
        underlyingResource.serve(newSender, exchange, completionCallback);
    } else {
        UndertowLogger.REQUEST_LOGGER.tracef("Serving resource %s from the buffer cache to %s", name, exchange);
        // serve straight from the cache
        ByteBuffer[] buffers;
        boolean ok = false;
        try {
            LimitedBufferSlicePool.PooledByteBuffer[] pooled = existing.buffers();
            buffers = new ByteBuffer[pooled.length];
            for (int i = 0; i < buffers.length; i++) {
                // Keep position from mutating
                buffers[i] = pooled[i].getBuffer().duplicate();
            }
            ok = true;
        } finally {
            if (!ok) {
                existing.dereference();
            }
        }
        sender.send(buffers, new DereferenceCallback(existing, completionCallback));
    }
}
Also used : Sender(io.undertow.io.Sender) ResponseCachingSender(io.undertow.server.handlers.cache.ResponseCachingSender) ResponseCachingSender(io.undertow.server.handlers.cache.ResponseCachingSender) DirectBufferCache(io.undertow.server.handlers.cache.DirectBufferCache) ByteBuffer(java.nio.ByteBuffer)

Aggregations

Sender (io.undertow.io.Sender)1 DirectBufferCache (io.undertow.server.handlers.cache.DirectBufferCache)1 ResponseCachingSender (io.undertow.server.handlers.cache.ResponseCachingSender)1 ByteBuffer (java.nio.ByteBuffer)1