Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  //
  //  ========================================================================
  //  Copyright (c) 1995-2013 Mort Bay Consulting Pty. Ltd.
  //  ------------------------------------------------------------------------
  //  All rights reserved. This program and the accompanying materials
  //  are made available under the terms of the Eclipse Public License v1.0
  //  and Apache License v2.0 which accompanies this distribution.
  //
  //      The Eclipse Public License is available at
 //      http://www.eclipse.org/legal/epl-v10.html
 //
 //      The Apache License v2.0 is available at
 //      http://www.opensource.org/licenses/apache2.0.php
 //
 //  You may elect to redistribute this code under either of these licenses.
 //  ========================================================================
 //
 
 package org.eclipse.jetty.server;
 
 
 
 
 /* ------------------------------------------------------------ */
 
 public class ResourceCache
 {
     private static final Logger LOG = Log.getLogger(ResourceCache.class);
 
     private final ConcurrentMap<String,Content_cache;
     private final AtomicInteger _cachedSize;
     private final AtomicInteger _cachedFiles;
     private final ResourceFactory _factory;
     private final ResourceCache _parent;
     private final MimeTypes _mimeTypes;
     private final boolean _etags;
 
     private boolean  _useFileMappedBuffer=true;
     private int _maxCachedFileSize =4*1024*1024;
     private int _maxCachedFiles=2048;
     private int _maxCacheSize =32*1024*1024;
     
     /* ------------------------------------------------------------ */
    
Constructor.

Parameters:
mimeTypes Mimetype to use for meta data
 
     public ResourceCache(ResourceCache parentResourceFactory factoryMimeTypes mimeTypes,boolean useFileMappedBuffer,boolean etags)
     {
          = factory;
         =new ConcurrentHashMap<String,Content>();
         =new AtomicInteger();
         =new AtomicInteger();
         =mimeTypes;
         =parent;
         =etags;
     }
 
     /* ------------------------------------------------------------ */
     public int getCachedSize()
     {
         return .get();
     }
     
     /* ------------------------------------------------------------ */
     public int getCachedFiles()
     {
         return .get();
     }
     
     /* ------------------------------------------------------------ */
     public int getMaxCachedFileSize()
     {
         return ;
     }
    /* ------------------------------------------------------------ */
    public void setMaxCachedFileSize(int maxCachedFileSize)
    {
         = maxCachedFileSize;
        shrinkCache();
    }
    /* ------------------------------------------------------------ */
    public int getMaxCacheSize()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    public void setMaxCacheSize(int maxCacheSize)
    {
         = maxCacheSize;
        shrinkCache();
    }
    /* ------------------------------------------------------------ */
    

Returns:
Returns the maxCachedFiles.
    public int getMaxCachedFiles()
    {
        return ;
    }
    
    /* ------------------------------------------------------------ */
    

Parameters:
maxCachedFiles The maxCachedFiles to set.
    public void setMaxCachedFiles(int maxCachedFiles)
    {
         = maxCachedFiles;
        shrinkCache();
    }
    /* ------------------------------------------------------------ */
    public boolean isUseFileMappedBuffer()
    {
        return ;
    }
    /* ------------------------------------------------------------ */
    public void setUseFileMappedBuffer(boolean useFileMappedBuffer)
    {
         = useFileMappedBuffer;
    }
    /* ------------------------------------------------------------ */
    public void flushCache()
    {
        if (!=null)
        {
            while (.size()>0)
            {
                for (String path : .keySet())
                {
                    Content content = .remove(path);
                    if (content!=null)
                        content.invalidate();
                }
            }
        }
    }
    /* ------------------------------------------------------------ */
    
Get a Entry from the cache. Get either a valid entry object or create a new one if possible.

Parameters:
pathInContext The key into the cache
Returns:
The entry matching pathInContext, or a new entry if no matching entry was found. If the content exists but is not cachable, then a org.eclipse.jetty.http.HttpContent.ResourceAsHttpContent instance is return. If the resource does not exist, then null is returned.
Throws:
java.io.IOException Problem loading the resource
    public HttpContent lookup(String pathInContext)
        throws IOException
    {
        // Is the content in this cache?
        Content content =.get(pathInContext);
        if (content!=null && (content).isValid())
            return content;
       
        // try loading the content from our factory.
        Resource resource=.getResource(pathInContext);
        HttpContent loaded = load(pathInContext,resource);
        if (loaded!=null)
            return loaded;
        
        // Is the content in the parent cache?
        if (!=null)
        {
            HttpContent httpContent=.lookup(pathInContext);
            if (httpContent!=null)
                return httpContent;
        }
        
        return null;
    }
    
    /* ------------------------------------------------------------ */
    

Parameters:
resource
Returns:
True if the resource is cacheable. The default implementation tests the cache sizes.
    protected boolean isCacheable(Resource resource)
    {
        long len = resource.length();
        // Will it fit in the cache?
        return  (len>0 && len< && len<);
    }
    
    /* ------------------------------------------------------------ */
    private HttpContent load(String pathInContextResource resource)
        throws IOException
    {
        Content content=null;
        
        if (resource==null || !resource.exists())
            return null;
        
        // Will it fit in the cache?
        if (!resource.isDirectory() && isCacheable(resource))
        {   
            // Create the Content (to increment the cache sizes before adding the content 
            content = new Content(pathInContext,resource);
            // reduce the cache to an acceptable size.
            shrinkCache();
            // Add it to the cache.
            Content added = .putIfAbsent(pathInContext,content);
            if (added!=null)
            {
                content.invalidate();
                content=added;
            }
            return content;
        }
        
        
    }
    
    /* ------------------------------------------------------------ */
    private void shrinkCache()
    {
        // While we need to shrink
        while (.size()>0 && (.get()> || .get()>))
        {
            // Scan the entire cache and generate an ordered list by last accessed time.
            SortedSet<Contentsortednew TreeSet<Content>(
                    new Comparator<Content>()
                    {
                        public int compare(Content c1Content c2)
                        {
                            if (c1._lastAccessed<c2._lastAccessed)
                                return -1;
                            
                            if (c1._lastAccessed>c2._lastAccessed)
                                return 1;
                            if (c1._length<c2._length)
                                return -1;
                            
                            return c1._key.compareTo(c2._key);
                        }
                    });
            for (Content content : .values())
                sorted.add(content);
            
            // Invalidate least recently used first
            for (Content content : sorted)
            {
                if (.get()<= && .get()<=)
                    break;
                if (content==.remove(content.getKey()))
                    content.invalidate();
            }
        }
    }
    
    /* ------------------------------------------------------------ */
    protected Buffer getIndirectBuffer(Resource resource)
    {
        try
        {
            int len=(int)resource.length();
            if (len<0)
            {
                .warn("invalid resource: "+String.valueOf(resource)+" "+len);
                return null;
            }
            Buffer buffer = new IndirectNIOBuffer(len);
            InputStream is = resource.getInputStream();
            buffer.readFrom(is,len);
            is.close();
            return buffer;
        }
        catch(IOException e)
        {
            .warn(e);
            return null;
        }
    }
    /* ------------------------------------------------------------ */
    protected Buffer getDirectBuffer(Resource resource)
    {
        try
        {
            if ( && resource.getFile()!=null
                return new DirectNIOBuffer(resource.getFile());
            int len=(int)resource.length();
            if (len<0)
            {
                .warn("invalid resource: "+String.valueOf(resource)+" "+len);
                return null;
            }
            Buffer buffer = new DirectNIOBuffer(len);
            InputStream is = resource.getInputStream();
            buffer.readFrom(is,len);
            is.close();
            return buffer;
        }
        catch(IOException e)
        {
            .warn(e);
            return null;
        }
    }
    /* ------------------------------------------------------------ */
    @Override
    public String toString()
    {
        return "ResourceCache["++","++"]@"+hashCode();
    }
    
    /* ------------------------------------------------------------ */
    /* ------------------------------------------------------------ */
    
MetaData associated with a context Resource.
    public class Content implements HttpContent
    {
        final Resource _resource;
        final int _length;
        final String _key;
        final long _lastModified;
        final Buffer _lastModifiedBytes;
        final Buffer _contentType;
        final Buffer _etagBuffer;
        
        volatile long _lastAccessed;
        /* ------------------------------------------------------------ */
        Content(String pathInContext,Resource resource)
        {
            =pathInContext;
            =resource;
            boolean exists=resource.exists();
            =exists?resource.lastModified():-1;
            =<0?null:new ByteArrayBuffer(HttpFields.formatDate());
            
            =exists?(int)resource.length():0;
            .addAndGet();
            .incrementAndGet();
            =System.currentTimeMillis();
            
            =?new ByteArrayBuffer(resource.getWeakETag()):null;
        }
        /* ------------------------------------------------------------ */
        public String getKey()
        {
            return ;
        }
        /* ------------------------------------------------------------ */
        public boolean isCached()
        {
            return !=null;
        }
        
        /* ------------------------------------------------------------ */
        public boolean isMiss()
        {
            return false;
        }
        /* ------------------------------------------------------------ */
        public Resource getResource()
        {
            return ;
        }
        /* ------------------------------------------------------------ */
        public Buffer getETag()
        {
            return ;
        }
        
        /* ------------------------------------------------------------ */
        boolean isValid()
        {
            if (==.lastModified() && ==.length())
            {
                =System.currentTimeMillis();
                return true;
            }
            if (this==.remove())
                invalidate();
            return false;
        }
        /* ------------------------------------------------------------ */
        protected void invalidate()
        {
            // Invalidate it
            .addAndGet(-);
            .decrementAndGet();
            .release(); 
        }
        /* ------------------------------------------------------------ */
        public Buffer getLastModified()
        {
            return ;
        }
        /* ------------------------------------------------------------ */
        public Buffer getContentType()
        {
            return ;
        }
        /* ------------------------------------------------------------ */
        public void release()
        {
            // don't release while cached. Release when invalidated.
        }
        /* ------------------------------------------------------------ */
        public Buffer getIndirectBuffer()
        {
            Buffer buffer = .get();
            if (buffer==null)
            {
                Buffer buffer2=ResourceCache.this.getIndirectBuffer();
                
                if (buffer2==null)
                    .warn("Could not load "+this);
                else if (.compareAndSet(null,buffer2))
                    buffer=buffer2;
                else
                    buffer=.get();
            }
            if (buffer==null)
                return null;
            return new View(buffer);
        }
        
        /* ------------------------------------------------------------ */
        public Buffer getDirectBuffer()
        {
            Buffer buffer = .get();
            if (buffer==null)
            {
                Buffer buffer2=ResourceCache.this.getDirectBuffer();
                if (buffer2==null)
                    .warn("Could not load "+this);
                else if (.compareAndSet(null,buffer2))
                    buffer=buffer2;
                else
                    buffer=.get();
            }
            if (buffer==null)
                return null;
                        
            return new View(buffer);
        }
        
        /* ------------------------------------------------------------ */
        public long getContentLength()
        {
            return ;
        }
        /* ------------------------------------------------------------ */
        public InputStream getInputStream() throws IOException
        {
            Buffer indirect = getIndirectBuffer();
            if (indirect!=null && indirect.array()!=null)
                return new ByteArrayInputStream(indirect.array(),indirect.getIndex(),indirect.length());
           
            return .getInputStream();
        }   
        /* ------------------------------------------------------------ */
        @Override
        public String toString()
        {
            return String.format("%s %s %d %s %s",,.exists(),.lastModified(),,);
        }   
    }
New to GrepCode? Check out our FAQ X