Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
   *
   * Copyright (c) 1997-2010 Oracle and/or its affiliates. All rights reserved.
   *
   * The contents of this file are subject to the terms of either the GNU
   * General Public License Version 2 only ("GPL") or the Common Development
   * and Distribution License("CDDL") (collectively, the "License").  You
   * may not use this file except in compliance with the License.  You can
  * obtain a copy of the License at
  * https://glassfish.dev.java.net/public/CDDL+GPL_1_1.html
  * or packager/legal/LICENSE.txt.  See the License for the specific
  * language governing permissions and limitations under the License.
  *
  * When distributing the software, include this License Header Notice in each
  * file and include the License file at packager/legal/LICENSE.txt.
  *
  * GPL Classpath Exception:
  * Oracle designates this particular file as subject to the "Classpath"
  * exception as provided by Oracle in the GPL Version 2 section of the License
  * file that accompanied this code.
  *
  * Modifications:
  * If applicable, add the following below the License Header, with the fields
  * enclosed by brackets [] replaced by your own identifying information:
  * "Portions Copyright [year] [name of copyright owner]"
  *
  * Contributor(s):
  * If you wish your version of this file to be governed by only the CDDL or
  * only the GPL Version 2, indicate your decision by adding "[Contributor]
  * elects to include this software in this distribution under the [CDDL or GPL
  * Version 2] license."  If you don't indicate a single choice of license, a
  * recipient has the option to distribute your version of this file under
  * either the CDDL, the GPL Version 2 or to extend the choice of license to
  * its licensees as provided above.  However, if you add GPL Version 2 code
  * and therefore, elected the GPL Version 2 license, then the option applies
  * only if the new code is made subject to such option by the copyright
  * holder.
  */
 
 package com.sun.enterprise.web.connector.grizzly;
 
 import java.io.File;
This class implements a file caching mechanism used to cache static resources.

Author(s):
Jeanfrancois Arcand
Scott Oaks
 
 public class FileCache{
     
     public final static String DEFAULT_SERVLET_NAME = "default";
   
    
    
A ByteBuffer cache of static pages.
    
     private final ConcurrentHashMap<String,FileCacheEntryfileCache = 
             new ConcurrentHashMap<String,FileCacheEntry>();
    
    
    
A dummy instance of ByteBuffer
 
     private final static ByteBuffer nullByteBuffer = 
                             (ByteBuffer) ByteBuffer.allocate(0);
  
    
    
A connection: close of ByteBuffer
 
     protected final static ByteBuffer connectionCloseBB = 
             ByteBuffer.wrap("Connection: close\r\n\r\n".getBytes());

    
A connection: keep-alive of ByteBuffer
 
     protected final static ByteBuffer connectionKaBB = 
             ByteBuffer.wrap("Connection: keep-alive\r\n\r\n".getBytes());
    
    
    
HTTP end line.
 
     private final static String NEWLINE = "\r\n";


    
HTTP OK header
    public final static String OK = "HTTP/1.1 200 OK" + ;    

    
The port associated with this cache.
    private int port = 8080;    
    
    
    
Scheduled Thread that clean the cache every XX seconds.
        = new ScheduledThreadPoolExecutor(1,
            new GrizzlyThreadFactory("FileCacheThread-" + ,
                1,.)); 
    
    
    
FileCacheEntry cache
    private Queue<FileCacheEntrycacheManager;

    
    
Timeout before remove the static resource from the cache.
    private int secondsMaxAge = -1;
    
    
    
The maximum entries in the fileCache
    private int maxCacheEntries = 1024;
    
 
    
The maximum size of a cached resources.
    private long minEntrySize = 2048;
            
               
    
The maximum size of a cached resources.
    private long maxEntrySize = 537600;
    
    
    
The maximum memory mapped bytes
    private long maxLargeFileCacheSize = 10485760;
            
    
    
The maximum cached bytes
    private long maxSmallFileCacheSize = 1048576;
    
    
    
The current cache size in bytes
    private static long mappedMemorySize = 0;
    
    
    
The current cache size in bytes
    private static long heapSize = 0;  
    
            
    
Is the file cache enabled.
    private boolean isEnabled = true;
        
    
    
Is the large FileCache enabled.
    private boolean isLargeFileCacheEnabled = true;   
    
    
    
Is monitoring enabled.
    private static boolean isMonitoringEnabled = false;
    
    
    
The number of current open cache entries
    private int openCacheEntries = 0;
   
       
    
The number of max current open cache entries
    private int maxOpenCacheEntries = 0;
    
    
    
Max heap space used for cache
    private long maxHeapCacheSize = 0;   
    
    
    
Max mapped memory used for cache
    private long maxMappedMemory = 0;   
    
    
    
Number of cache lookup hits
    private int countHits = 0;
    
    
    
Number of cache lookup misses
    private int countMisses = 0;
    
    
    
Number of hits on cached file info
    private int countCacheHits;
    
    
    
Number of misses on cached file info
    private int countCacheMisses;
        
    
    
Number of hits on cached file info
    private int countMappedHits;
    
    
    
Number of misses on cached file info
    private int countMappedMisses;

    
    
The Header ByteBuffer default size.
    private int headerBBSize = 4096;
    // ---------------------------------------------------- Methods ----------//
             
            
    
Add a resource to the cache. Currently, only static resources served by the DefaultServlet can be cached.
    public synchronized void add(String mappedServletString baseDir
            String requestURIMimeHeaders headersboolean xPoweredBy){
        
        if ( .get(requestURI) != nullreturn;
        
        // cache is full.
        if ( .size() > ) {
            return;
        }
        
        if ( mappedServlet.equals() ){                                     
            File file = new File(baseDir + requestURI);
            ByteBuffer bb = mapFile(file);
            // Always put the answer into the map. If it's null, then
            // we know that it doesn't fit into the cache, so there's no
            // reason to go through this code again.
            if (bb == null)
                bb = ;
            
            FileCacheEntry entry = .poll();
            if ( entry == null){
                entry = new FileCacheEntry();
            }
            entry.bb = bb;
            entry.requestURI = requestURI;
            
            if ( bb != ){
                entry.lastModified = headers.getHeader("Last-Modified");
                entry.contentType = headers.getHeader("content-type");
                entry.xPoweredBy = xPoweredBy;
                entry.isInHeap = (file.length() < );
                entry.date = headers.getHeader("Date");
                entry.Etag = headers.getHeader("Etag");
                configHeaders(entry);
                if (  ) {
                    ++;   
                    if (  > ){
                         = ;
                    }
                    if (  > ){
                         = ;
                    }
                    if (  > ){
                         = ;
                    }
                }
                if (  > 0 ) {
                    entry.future = .schedule(entry
                                                .);
                }
            }
            .put(requestURI,entry);
        }            
    }
       
    
    
Map the file to a ByteBuffer

Returns:
the ByteBuffer
    private final ByteBuffer mapFile(File file){
        FileChannel fileChannel = null;
        FileInputStream stream = null;
        try {
            stream = new FileInputStream(file);
            fileChannel = stream.getChannel();
             
            long size = fileChannel.size();
            
            if ( ! ) {
                // Large file support are not enabled
                if ( size >  ) {
                    return null;
                }
            } else if ( size > ){
                return null;
            }
            if ( size >  )
                += size;
            else
                += size;
 
            // Cache full
            if (  >  ) {
                -= size;
                return null;
            } else  if (  >  ) {
                -= size;
                return null;
            }        
            
            ByteBuffer bb = 
                    fileChannel.map(..,0,size);
                                 
            if ( size < ) {
                ((MappedByteBuffer)bb).load();
            }
            return bb;
        } catch (IOException ioe) {
            return null;
        } finally {
            if (stream != null) {
                try {
                    stream.close();
                } catch (IOException ioe) {
                }
            }
            if (fileChannel != null) {
                try {
                    fileChannel.close();
                } catch (IOException ioe) {
                }
            }
        }
    }
        
    
    
Return true if the file is cached.
    private final FileCacheEntry map(byte[] requestBytes,int startint length){
        String uri = "";
        FileCacheEntry entry = null;
        
        if ( !.isEmpty() ){
            uri = new String(requestBytes,start,length);
            entry = .get(uri);
            
            if ( ) {
                if (entry != null && entry.bb != null 
                        && entry.bb != ){
                    if ( entry.isInHeap ) 
                        ++;
                    else
                        ++;
                    ++;
                
                } else {
                  ++;
                }
            }
        }
        return entry;
    }
      
    
    
Send the cache.
    public boolean sendCache(byte[] reqint startint length,
            SocketChannel socketChannelboolean keepAlive){
        try{
            FileCacheEntry entry = map(req,start,length);
            if ( entry != null && entry.bb != ){
                sendCache(socketChannel,entry,keepAlive); 
                return true;
            }
        } catch (IOException ex){
            SelectorThread.logger()
                .fine("File Cache: " + ex.getMessage());
            return true;
        } catch (Throwable t){
            // If an unexpected exception occurs, try to serve the page
            // as if it wasn't in a cache.
            SelectorThread.logger()
                .fine("File Cache thread race: " + t.getMessage());
        }
        return false;
    }    
     
    
    
Set the cache manager used by this instance.
    public void setCacheManager(Queue cacheManager){
        this. = cacheManager;
    }   
    
    
    // -------------------------------------------------- Static cache -------/
    
    
    
Send the cached resource.
    protected void sendCache(SocketChannel socketChannel,  FileCacheEntry entry,
            boolean keepAlivethrows IOException{
  
        OutputWriter.flushChannel(socketChannelentry.headerBuffer.slice());
        ByteBuffer keepAliveBuf = keepAlive ? .slice():
               .slice();
        OutputWriter.flushChannel(socketChannelkeepAliveBuf);        
        OutputWriter.flushChannel(socketChannelentry.bb.slice());
    }

    
    
Return a ByteBuffer contains the server header.
    private void configHeaders(FileCacheEntry entry) {
        if ( entry.headerBuffer == null ) {
            entry.headerBuffer = 
                    ByteBuffer.allocate(getHeaderBBSize());
        }
        
        StringBuffer sb = new StringBuffer();
        sb.append();
        if ( entry.xPoweredBy){
            appendHeaderValue(sb,"X-Powered-By""Servlet/2.5");
        }     
        appendHeaderValue(sb"ETag"entry.Etag);   
        appendHeaderValue(sb,"Last-Modified"entry.lastModified);
        appendHeaderValue(sb,"Content-Type"entry.contentType);
        appendHeaderValue(sb,"Content-Length"entry.bb.capacity() + "");
        appendHeaderValue(sb,"Date"entry.date);
        appendHeaderValue(sb,"Server".);
        entry.headerBuffer.put(sb.toString().getBytes());
        entry.headerBuffer.flip();
    }   
       
    
    
Utility to add headers to the HTTP response.
    private void appendHeaderValue(StringBuffer sb,String nameString value) {
        sb.append(name);
        sb.append(": ");
        sb.append(value);
        sb.append();
    }   
    
    public final class FileCacheEntry implements Runnable{       
        public String requestURI;
        public String lastModified;
        public String contentType;
        public ByteBuffer bb;
        public ByteBuffer headerBuffer;        
        public boolean xPoweredBy;
        public boolean isInHeap = false;
        public String date;
        public String Etag;
        public Future future;
             
        public void run(){                          
            .remove();
            
            if ( == nullreturn;
            
            if ( != null) {

                
If the position !=0, it means the ByteBuffer has a view that is still used. If that's the case, wait another 10 seconds before marking the ByteBuffer for garbage collection
                if ( .position() !=0 || .position() != 0 ){        
                     = 
                                .schedule(this, 10, .);
                    return;
                } 
                if ( ! )
                     -= .limit();
                else
                     -= .limit();
                 = null;
                 = null;
                --;
            }
            
            if (  != null ) {
                .cancel(false);
                 = null;
            }
             = null;
            .offer(this);
        }
    }
    
    
    // ---------------------------------------------------- Monitoring --------//
    
    
    
Returns flag indicating whether file cache has been enabled

Returns:
1 if file cache has been enabled, 0 otherwise
    public int getFlagEnabled() {
        return ( == true?1:0);
    }
    
    
    
Return the maximum age of a valid cache entry

Returns:
cache entry maximum age
    public int getSecondsMaxAge() {
        return ;
    }
    
    
    
Return the number of current cache entries.

Returns:
current cache entries
    public long getCountEntries() {
        return .size();
    }
    
    
    
Return the maximum number of cache entries

Returns:
maximum cache entries
    public long getMaxEntries() {
        return ;
    }
    
    
    
The number of current open cache entries

Returns:
open cache entries
    public long getCountOpenEntries() {
        return ;
    }
    
    
    
Return the maximum number of open cache entries

Returns:
maximum open cache entries
    public long getMaxOpenEntries() {
       return ;        
    }
    
    
    
Return the heap space used for cache

Returns:
heap size
    public long getSizeHeapCache() {
        return ;
    }
    
    
    
Return the maximum heap space used for cache

Returns:
maximum heap size
    public long getMaxHeapCacheSize() {
        return ;
    }
    
    
    
Return the size of Mapped memory used for caching

Returns:
Mapped memory size
    public static long getSizeMmapCache() {
        return ;
    }
    
    
    
Return the Maximum Memory Map size to be used for caching

Returns:
maximum Memory Map size
    public long getMaxMmapCacheSize() {
        return ;
    }
    
    
    
Return the Number of cache lookup hits

Returns:
cache hits
    public long getCountHits() {
        return ;
    }
    
    
    
Return the Number of cache lookup misses

Returns:
cache misses
    public long getCountMisses() {
        return ;
    }
    
    
    
The Number of hits on cached file info

Returns:
hits on cached file info
    public long getCountInfoHits() {
        return ;
    }
    
    
    
Return the number of misses on cached file info

Returns:
misses on cache file info
    public long getCountInfoMisses() {
        return ;
    }
    
    
    
Return the Number of hits on cached file content

Returns:
hits on cache file content
    public long getCountContentHits() {
        return ;
    }
    
    
    
Return the Number of misses on cached file content

Returns:
missed on cached file content
    public int getCountContentMisses() {
        return ;
    }
    
    // ---------------------------------------------------- Properties ----- //
    
    
    
Turn monitoring on/off
    public static void setIsMonitoringEnabled(boolean isMe){
         = isMe;
    }
    
     
    
    
The timeout in seconds before remove a FileCacheEntry from the fileCache
    public void setSecondsMaxAge(int sMaxAges){
         = sMaxAges;
    }
    
    
    
Set the maximum entries this cache can contains.
    public void setMaxCacheEntries(int mEntries){
         = mEntries;
    }

    
    
Return the maximum entries this cache can contains.
    
    public int getMaxCacheEntries(){
        return ;
    }
    
    
    
Set the maximum size a FileCacheEntry can have.
    public void setMinEntrySize(long mSize){
         = mSize;
    }
    
    
    
Get the maximum size a FileCacheEntry can have.
    public long getMinEntrySize(){
        return ;
    }
     
    
    
Set the maximum size a FileCacheEntry can have.
    public void setMaxEntrySize(long mEntrySize){
         = mEntrySize;
    }
    
    
    
Get the maximum size a FileCacheEntry can have.
    public long getMaxEntrySize(){
        return ;
    }
    
    
    
Set the maximum cache size
 
    public void setMaxLargeCacheSize(long mCacheSize){
         = mCacheSize;
    }

    
    
Get the maximum cache size
 
    public long getMaxLargeCacheSize(){
        return ;
    }
    
    
    
Set the maximum cache size
 
    public void setMaxSmallCacheSize(long mCacheSize){
         = mCacheSize;
    }
    
    
    
Get the maximum cache size
 
    public long getMaxSmallCacheSize(){
        return ;
    }    

    
    
Is the fileCache enabled.
    public boolean isEnabled(){
        return ;
    }

    
    
Is the file caching mechanism enabled.
    public void setIsEnabled(boolean isEnabled){
        this. = isEnabled;
    }
   
    
    
Is the large file cache support enabled.
    public void setLargeFileCacheEnabled(boolean isLargeEnabled){
        this. = isLargeEnabled;
    }
   
    
    
Is the large file cache support enabled.
    public boolean getLargeFileCacheEnabled(){
        return ;
    }    
    
    
    
Return the FileCache
    public ConcurrentHashMap getCache(){
        return ;
    }

    
    
Retunr the header size buffer.
 
    public int getHeaderBBSize() {
        return ;
    }

    
Set the size of the header ByteBuffer.
    public void setHeaderBBSize(int headerBBSize) {
        this. = headerBBSize;
    }
New to GrepCode? Check out our FAQ X