Remove certain item or clear whole OmniFaces cache

The Omnifaces o:cache Component is a useful Tool when trying to speed up you jsf powered website.

But in some situations you need to remove a certain item from the cache or you want to clear the whole cache, while there seems to be a way (Example 4) to remove single items by Key we couldn’t find a ‘official’ way to clear the whole cache.

 

Here is our Solution to the Problem:

public static boolean removeOmniCacheItem(String key) {    	
	Map<string , Object> applicationMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
 
	if (applicationMap.containsKey(DefaultCacheProvider.DEFAULT_CACHE_PARAM_NAME)) {
		synchronized (DefaultCacheProvider.class) {
			if (applicationMap.containsKey(DefaultCacheProvider.DEFAULT_CACHE_PARAM_NAME)) {
				((Cache)applicationMap.get(DefaultCacheProvider.DEFAULT_CACHE_PARAM_NAME)).remove(key);
				return true;
			}				
		}
	}
 
	return false;
}
 
public static boolean clearOmniCache() {    	
	Map</string><string , Object> applicationMap = FacesContext.getCurrentInstance().getExternalContext().getApplicationMap();
 
	if (applicationMap.containsKey(DefaultCacheProvider.DEFAULT_CACHE_PARAM_NAME)) {
		synchronized (DefaultCacheProvider.class) {
			if (applicationMap.containsKey(DefaultCacheProvider.DEFAULT_CACHE_PARAM_NAME)) {
				applicationMap.remove(DefaultCacheProvider.DEFAULT_CACHE_PARAM_NAME);
				return true;
			}				
		}
	}
 
	return false;
}
</string>

Those Methods assume that you use the Application Scope, when using an other Scope you have to change the corresponding lines.

Using this methods we could finally make use of the great speed improvements a Cache usually, and especially o:cache offers.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.