/**
 * 
 */
package com.trendrr.oss;

import java.util.concurrent.ConcurrentHashMap;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.trendrr.oss.concurrent.ReinitObject;


/**
 * 
 * A threadsafe file cache.
 * 
 * 
 * @author Dustin Norlander
 * @created Apr 7, 2011
 * 
 */
public class FileCache {

	protected Log log = LogFactory.getLog(FileCache.class);
	
	private static ConcurrentHashMap<String, ReinitObject<byte[]>> cache = new ConcurrentHashMap<String, ReinitObject<byte[]>> ();
	
	
	/**
	 * loads a file from the cache.  All exceptions are logged as warnings, and null is returned.
	 * @param filename filename to load
	 * @param timeoutPeriod number of milliseconds between reload of the file.
	 * @return
	 */
	public byte[] getFileBytes(String filename, long timeoutPeriod) {
		final String f = filename;
		
		//fancy timeout cache. 
		cache.putIfAbsent(filename, new ReinitObject<byte[]>(timeoutPeriod) {
			@Override
			public byte[] init() {
				try {
					System.out.println("LOADING FROM FILE SYSTEM!");
					return FileHelper.loadBytes(f);
				} catch (Exception e) {
					log.warn("Caught", e);
				}
				return null;
			}
		});
		return cache.get(filename).get();
	}
}

@@ -31,16 +31,61 @@
 r.oss;%0A%0A
+import java.io.UnsupportedEncodingException;%0A
 import j
@@ -576,16 +576,695 @@
 %5B%5D%3E%3E ();
+%0A%0A%09//absolute max number of items to cache.%0A%09private int maxItems = 200;%0A%0A%09/**%0A%09 * max number of items to cache. %0A%09 * %0A%09 * this is a hard limit.  %0A%09 * @return%0A%09 */%0A%09public int getMaxItems() %7B%0A%09%09return maxItems;%0A%09%7D%0A%0A%0A%09public void setMaxItems(int maxItems) %7B%0A%09%09this.maxItems = maxItems;%0A%09%7D%0A%0A%0A%09/**%0A%09 * gets the file as a utf8 string or null;%0A%09 * @param filename%0A%09 * @param timeoutPeriod%0A%09 * @return%0A%09 */%0A%09public String getFileString(String filename, long timeoutPeriod) %7B%0A%09%09byte%5B%5D bytes = this.getFileBytes(filename, timeoutPeriod);%0A%09%09if (bytes == null)%0A%09%09%09return null;%0A%09%09try %7B%0A%09%09%09return new String(bytes, %22UTF8%22);%0A%09%09%7D catch (UnsupportedEncodingException e) %7B%0A%09%09%09return null;%0A%09%09%7D%0A%09%7D
 %0A%09%0A%09%0A%09/*
@@ -1557,16 +1557,232 @@
 riod) %7B%0A
+%09%09if (cache.size() %3E this.maxItems) %7B%0A%09%09%09//TODO: this could cause a threadsafety problem below%0A%09%09%09//this should be smarter, but for now this is only a %0A%09%09%09//catch for a potential memory leak%0A%09%09%09cache.clear();%0A%09%09%7D%0A%09%09%0A
 %09%09final 

Add max for filecache