Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Remco van 't Veer http://blog.remvee.net

« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS 

avoid web caching

// Set to expire far in the past.
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");

time based cache

A simple time based cache build around a map store.

import java.util.Map;
import java.util.WeakHashMap;

/**
 * Simple time-based cache.
 */
public class SimpleCache {
	private long maxAge;
	private Map store;

	/**
	 * Instanciate a cache with max age of 1 hour and a WeakHashMap as store.
	 * @see java.util.WeakHashMap
	 */
	public SimpleCache() {
		this.maxAge = 1000 * 60 * 60;
		this.store = new WeakHashMap();
	}
	
	/**
	 * @param maxAge maximum age of an entry in milliseconds
	 * @param store map to hold entries
	 */
	public SimpleCache(long maxAge, Map store) {
		this.maxAge = maxAge;
		this.store = store;
	}
	
	/**
	 * Cache an object.
	 * @param key unique identifier to retrieve object
	 * @param value object to cache
	 */
	public void put(Object key, Object value) {
		store.put(key, new Item(value));
	}
	
	/**
	 * Fetch an object.
	 * @param key unique identifier to retrieve object
	 * @return an object or null in case it isn't stored or it expired
	 */
	public Object get(Object key) {
		Item item = getItem(key);
		return item == null ? null : item.payload;
	}
	
	/**
	 * Fetch an object or store and return output of callback.
	 * @param key unique identifier to retrieve object
	 * @param block code executed when object not in cache
	 * @return an object
	 */
	public synchronized Object get(Object key, Callback block) {
		Item item = getItem(key);
		if (item == null) {
			Object value = block.execute();
			item = new Item(value);
			store.put(key, item);
		}
		return item.payload;
	}
	
	/**
	 * Remove an object from cache.
	 * @param key unique identifier to retrieve object
	 */
	public void remove(Object key) {
		store.remove(key);
	}
	
	/**
	 * Get an item, if it expired remove it from cache and return null.
	 * @param key unique identifier to retrieve object
	 * @return an item or null
	 */
	private Item getItem(Object key) {
		Item item = (Item) store.get(key);
		if (item == null) {
			return null;
		}
		if (System.currentTimeMillis() - item.birth > maxAge) {
			store.remove(key);
			return null;
		}
		return item;		
	}

	/**
	 * Value container.
	 */
	private static class Item {
		long birth;
		Object payload;
		Item(Object payload) {
			this.birth = System.currentTimeMillis();
			this.payload = payload;
		}
	}
	
	/**
	 * A visitor interface.
	 */
	public static interface Callback {
		Object execute();
	}
}


And a couple of junit tests:

import java.util.HashMap;

import junit.framework.TestCase;

public class SimpleCacheTest extends TestCase {
	public void testPutGet () {
		SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap());
		c.put("key1", "value1");
		assertEquals("value1", c.get("key1"));
		c.put("key1", "value1.0");
		assertEquals("value1.0", c.get("key1"));
		c.put("key2", "value2");
		assertEquals("value2", c.get("key2"));
		assertEquals("value1.0", c.get("key1"));
	}
	
	public void testMaxAge () throws InterruptedException {
		SimpleCache c = new SimpleCache(1000, new HashMap());
		c.put("key1", "value1");
		assertEquals("value1", c.get("key1"));
		Thread.sleep(1500);
		assertNull(c.get("key1"));
		
		c.put("key2", "value2");
		Thread.sleep(750);
		c.put("key3", "value3");
		Thread.sleep(750);
		assertNull(c.get("key2"));
		assertNotNull(c.get("key3"));
		Thread.sleep(750);
		assertNull(c.get("key3"));
	}
	
	public void testRemove () {
		SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap());
		c.remove("key");
		assertNull(c.get("key"));
		c.put("key", "value");
		assertNotNull(c.get("key"));
		c.remove("key");
		assertNull(c.get("key"));
	}
	
	public void testCallBack () {
		SimpleCache c = new SimpleCache(Long.MAX_VALUE, new HashMap());
		assertEquals("value1", c.get("key1", new SimpleCache.Callback() {
			public Object execute() {
				return "value1";
			}
		}));
		assertEquals("value1", c.get("key1"));
		
		// again with a new callback (value)
		c.get("key1", new SimpleCache.Callback() {
			public Object execute() {
				return "value2";
			}
		});
		assertEquals("value1", c.get("key1"));
	}
}

Slurp InputStream to String

public static String slurp (InputStream in) throws IOException {
    StringBuffer out = new StringBuffer();
    byte[] b = new byte[4096];
    for (int n; (n = in.read(b)) != -1;) {
        out.append(new String(b, 0, n));
    }
    return out.toString();
}

find files in zip, jar, war, ear and nested archives

The following java class takes two arguments; a directory name and a regular expression. The directory is searched for files matching the regexp. Zip files (and zip-alikes) are also searched including nested zips.

import java.io.*;
import java.util.*;
import java.util.zip.*;

public class Finder {
	public static void main(String[] args) throws Exception {
		String path = args[0];
		final String expr = args[1];

		List l = new ArrayList();
		findFile(new File(path), new P() {
			public boolean accept(String t) {
				return t.matches(expr) || isZip(t);
			}
		}, l);

		List r = new ArrayList();
		for (Iterator it = l.iterator(); it.hasNext();) {
			File f = (File) it.next();
			String fn = f + "";
			if (fn.matches(expr)) r.add(fn);
			if (isZip(f.getName())) {
				findZip(fn, new FileInputStream(f), new P() {
					public boolean accept(String t) {
						return t.matches(expr);
					}
				}, r);
			}
		}

		for (Iterator it = r.iterator(); it.hasNext();) {
			System.out.println(it.next());
		}
	}

	static void findFile(File f, P p, List r) {
		if (f.isDirectory()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) findFile(files[i], p, r);
		} else if (p.accept(f + "")) {
			r.add(f);
		}
	}

	static void findZip(String f, InputStream in, P p, List r) throws IOException {
		ZipInputStream zin = new ZipInputStream(in);

		ZipEntry en;
		while ((en = zin.getNextEntry()) != null) {
			if (p.accept(en.getName())) r.add(f + "!" + en);
			if (isZip(en.getName())) findZip(f + "!" + en, zin, p, r);
		}
	}

	static String[] ZIP_EXTENSIONS = { ".zip", ".jar", ".war", ".ear" };

	static boolean isZip(String t) {
		for (int i = 0; i < ZIP_EXTENSIONS.length; i++) {
			if (t.endsWith(ZIP_EXTENSIONS[i])) {
				return true;
			}
		}
		return false;
	}

	static interface P {
		public boolean accept(String t);
	}
}



Files are not properly closed! Don't use this class in a long running application or properly close all streams.
« Newer Snippets
Older Snippets »
Showing 1-4 of 4 total  RSS