Author: nbelaevski
Date: 2010-06-12 18:25:33 -0400 (Sat, 12 Jun 2010)
New Revision: 17619
Added:
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/ehcache-failsafe-richfaces.xml
root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/lru/
root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/lru/CacheMapTest.java
Removed:
root/core/trunk/impl/src/test/resources/oscache.properties
Modified:
root/core/trunk/api/src/main/java/org/ajax4jsf/cache/CacheFactory.java
root/core/trunk/api/src/main/java/org/richfaces/skin/Skin.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java
root/core/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java
root/core/trunk/impl/src/main/java/org/richfaces/application/InitializationListener.java
root/core/trunk/impl/src/main/java/org/richfaces/application/ServiceTrackerLockPhaseListener.java
root/core/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java
root/core/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java
root/core/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/oscache.properties
root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java
root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java
Log:
Resources framework redesigned to work with MyFaces 2.0
Added support for maximum cache size parameter
Unit tests for resources fwk updated
Modified: root/core/trunk/api/src/main/java/org/ajax4jsf/cache/CacheFactory.java
===================================================================
--- root/core/trunk/api/src/main/java/org/ajax4jsf/cache/CacheFactory.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/api/src/main/java/org/ajax4jsf/cache/CacheFactory.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -25,6 +25,8 @@
import java.util.Map;
+import javax.faces.context.FacesContext;
+
/**
* CacheFactory is a service provider specific interface.
* Service provider should implement CacheFactory to provide
@@ -41,5 +43,7 @@
* @return an implementation specific Cache object.
* @throws CacheException if any error occurs.
*/
- public Cache createCache(Map<?, ?> env);
+ public Cache createCache(FacesContext facesContext, String cacheName, Map<?, ?>
env);
+
+ public void destroy();
}
Modified: root/core/trunk/api/src/main/java/org/richfaces/skin/Skin.java
===================================================================
--- root/core/trunk/api/src/main/java/org/richfaces/skin/Skin.java 2010-06-11 17:44:40 UTC
(rev 17618)
+++ root/core/trunk/api/src/main/java/org/richfaces/skin/Skin.java 2010-06-12 22:25:33 UTC
(rev 17619)
@@ -269,7 +269,7 @@
* @param context -
* {@link FacesContext } for current request.
* @param name
- * name of paremeter.
+ * name of parameter.
* @return value of parameter in config, or null
*/
public Object getParameter(FacesContext context, String name);
@@ -288,9 +288,36 @@
public Object getParameter(FacesContext context, String name, Object defaultValue);
/**
+ * Get value for configuration parameter & interpret it as color string.
+ * If parameter set as EL-expression, calculate it value.
+ *
+ * @param context -
+ * {@link FacesContext } for current request.
* @param name
+ * name of parameter.
+ * @return value of parameter in config, or null
+ * @since 4.0.M1
+ */
+ public Integer getColorParameter(FacesContext context, String name);
+
+ /**
+ * Get value for configuration parameter & interpret it as color string.
+ * If parameter set as EL-expression, calculate it value.
+ *
+ * @param context -
+ * {@link FacesContext } for current request.
+ * @param name
+ * name of parameter.
+ * @param defaultValue - default value if parameter not present in Skin
* @return
+ * @since 4.0.M1
*/
+ public Integer getColorParameter(FacesContext context, String name, Object
defaultValue);
+
+ /**
+ * @param name
+ * @return
+ */
public boolean containsProperty(String name);
/**
Modified: root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java
===================================================================
--- root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -23,11 +23,12 @@
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.MessageFormat;
-import java.util.Collections;
-import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
+import javax.faces.context.FacesContext;
+
import org.ajax4jsf.cache.lru.LRUMapCacheFactory;
import org.ajax4jsf.resource.util.URLToStreamHelper;
import org.richfaces.log.RichfacesLogger;
@@ -44,39 +45,22 @@
"org.ajax4jsf.cache.EhCacheCacheFactory"};
private static final String FACTORY_PROPERTY_NAME =
"org.ajax4jsf.cache.CacheFactory";
private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
- private static final CacheManager INSTANCE = new CacheManager();
- // REVIEW brian(a)quiotix.com
- // Should this be a HashMap<String, WeakReference<Cache>>?
- private final Map<String, Cache> caches = Collections.synchronizedMap(new
HashMap<String, Cache>());
+ private CacheFactory cacheFactory;
+
+ private final Map<String, Cache> caches = new ConcurrentHashMap<String,
Cache>(1, 0.75f, 1);
- /**
- * Returns the singleton CacheManager
- */
- public static CacheManager getInstance() {
- return INSTANCE;
- }
-
public Cache getCache(String cacheName) {
return caches.get(cacheName);
}
- public Cache getNewCache(String cacheName, Map<?, ?> env) {
- createCache(cacheName, env);
+ public Cache createCache(FacesContext facesContext, String cacheName, Map<?, ?>
env) {
+ CacheFactory factory = getCacheFactory(env);
+ Cache cache = factory.createCache(facesContext, cacheName, env);
- return getCache(cacheName);
- }
-
- public void registerCache(String cacheName, Cache cache) {
caches.put(cacheName, cache);
- }
- public void createCache(String cacheName, Map<?, ?> env) {
- CacheFactory factory = getCacheFactory(env);
- Cache cache = factory.createCache(env);
-
- registerCache(cacheName, cache);
- cache.start();
+ return cache;
}
public void destroyCache(String cacheName) {
@@ -85,7 +69,11 @@
cache.stop();
}
- public CacheFactory getCacheFactory(Map<?, ?> env) {
+ private CacheFactory getCacheFactory(Map<?, ?> env) {
+ if (cacheFactory != null) {
+ return cacheFactory;
+ }
+
String[] factories;
String configuredFactoryName = findFactory(FACTORY_PROPERTY_NAME, env);
@@ -101,20 +89,22 @@
for (String factoryName : factories) {
try {
Class<?> spiClass = Class.forName(factoryName, true, loader);
- CacheFactory cacheFactory =
CacheFactory.class.cast(spiClass.newInstance());
-
+ cacheFactory = CacheFactory.class.cast(spiClass.newInstance());
LOG.info(MessageFormat.format("Selected [{0}]", factoryName));
-
- return cacheFactory;
- } catch (Throwable iae) {
-
+ break;
+ } catch (LinkageError iae) {
// TODO LOG debug
+ } catch (Exception e) {
+ // TODO LOG debug
}
}
- LOG.info("Selected fallback cache factory");
-
- return new LRUMapCacheFactory();
+ if (cacheFactory == null) {
+ cacheFactory = new LRUMapCacheFactory();
+ LOG.info("Selected fallback cache factory");
+ }
+
+ return cacheFactory;
}
public Map<String, Cache> getCaches() {
@@ -237,5 +227,9 @@
for (String cacheName : caches.keySet()) {
destroyCache(cacheName);
}
+
+ if (cacheFactory != null) {
+ cacheFactory.destroy();
+ }
}
}
Modified: root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java
===================================================================
--- root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -3,30 +3,37 @@
*/
package org.ajax4jsf.cache;
+import java.util.Date;
+
import net.sf.ehcache.Ehcache;
import net.sf.ehcache.Element;
-import java.util.Date;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class EhCacheCache implements org.ajax4jsf.cache.Cache {
+
private net.sf.ehcache.Ehcache cache;
-
- public EhCacheCache(Ehcache cache) {
+ private boolean preconfiguredCache;
+
+ public EhCacheCache(Ehcache cache, boolean preconfiguredCache) {
super();
this.cache = cache;
+ this.preconfiguredCache = preconfiguredCache;
}
public void start() {
- cache.initialise();
- cache.bootstrap();
+ if (!preconfiguredCache) {
+ cache.initialise();
+ cache.bootstrap();
+ }
}
public void stop() {
- cache.dispose();
+ if (!preconfiguredCache) {
+ cache.dispose();
+ }
}
public Object get(Object key) {
Modified: root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -3,23 +3,74 @@
*/
package org.ajax4jsf.cache;
+import java.net.URL;
+import java.text.MessageFormat;
+import java.util.Map;
+
+import javax.faces.context.FacesContext;
+
+import net.sf.ehcache.CacheManager;
+import net.sf.ehcache.Ehcache;
+
+import org.ajax4jsf.context.ContextInitParameters;
import org.richfaces.log.RichfacesLogger;
import org.slf4j.Logger;
-import java.util.Map;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
public class EhCacheCacheFactory implements CacheFactory {
+
private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
- public Cache createCache(Map<?, ?> env) {
- LOG.info("Creating EhCache cache instance");
+ private CacheManager cacheManager;
+
+ public EhCacheCacheFactory() {
+ super();
+
+ URL configUrl = null;
+
+ ClassLoader ccl = Thread.currentThread().getContextClassLoader();
+ if (ccl != null) {
+ configUrl = ccl.getResource("ehcache.xml");
+ }
- net.sf.ehcache.Ehcache cache = new
net.sf.ehcache.Cache("org.richfaces", 256, false, true, 0, 0);
+ if (configUrl != null) {
+ LOG.info(MessageFormat.format("Using cache configuration: {0}",
configUrl.toExternalForm()));
+ } else {
+ configUrl =
EhCacheCacheFactory.class.getResource("ehcache-failsafe-richfaces.xml");
+ LOG.info(MessageFormat.format("Using default cache configuration:
{0}", configUrl.toExternalForm()));
+ }
- return new EhCacheCache(cache);
+ cacheManager = CacheManager.create(configUrl);
}
+
+ public Cache createCache(FacesContext facesContext, String cacheName, Map<?, ?>
env) {
+ LOG.info("Creating EhCache cache instance");
+
+ int maxCacheSize = ContextInitParameters.getResourcesCacheSize(facesContext);
+ boolean preconfiguredCache = false;
+
+ Ehcache ehcache = cacheManager.getEhcache(cacheName);
+ if (ehcache == null) {
+ ehcache = new net.sf.ehcache.Cache(cacheName, maxCacheSize, false, true, 0,
0);
+ } else {
+ preconfiguredCache = true;
+
+ if (ehcache.getCacheConfiguration().getMaxElementsInMemory() <= 0) {
+ LOG.info(MessageFormat.format("Maximum cache size hasn''t
been set, resetting to {0} max items", maxCacheSize));
+
+ ehcache.getCacheConfiguration().setMaxElementsInMemory(maxCacheSize);
+ }
+ }
+
+ return new EhCacheCache(ehcache, preconfiguredCache);
+ }
+
+ public void destroy() {
+ cacheManager.shutdown();
+ cacheManager = null;
+ }
+
}
Modified:
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/JBossCacheCacheFactory.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -3,28 +3,37 @@
*/
package org.ajax4jsf.cache;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.text.MessageFormat;
+import java.util.Map;
+
+import javax.faces.FacesException;
+import javax.faces.context.FacesContext;
+
+import org.ajax4jsf.context.ContextInitParameters;
import org.ajax4jsf.resource.util.URLToStreamHelper;
import org.jboss.cache.Cache;
import org.jboss.cache.DefaultCacheFactory;
import org.jboss.cache.Fqn;
import org.jboss.cache.config.Configuration;
+import org.jboss.cache.config.EvictionAlgorithmConfig;
import org.jboss.cache.config.EvictionConfig;
import org.jboss.cache.config.EvictionRegionConfig;
+import org.jboss.cache.eviction.EvictionAlgorithmConfigBase;
import org.jboss.cache.eviction.ExpirationAlgorithmConfig;
+import org.richfaces.log.RichfacesLogger;
+import org.slf4j.Logger;
-import javax.faces.FacesException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.Map;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
+public class JBossCacheCacheFactory implements CacheFactory {
-//TODO - to doc - no max size eviction support
-public class JBossCacheCacheFactory implements CacheFactory {
+ private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
+
private org.jboss.cache.CacheFactory<String, Object> cacheFactory;
public JBossCacheCacheFactory() {
@@ -32,13 +41,29 @@
cacheFactory = new DefaultCacheFactory<String, Object>();
}
- public org.ajax4jsf.cache.Cache createCache(Map<?, ?> env) {
+ private void setupMaxSizeEviction(FacesContext facesContext, Cache<String,
Object> cache) {
+ EvictionConfig evictionConfig = cache.getConfiguration().getEvictionConfig();
+ EvictionAlgorithmConfig evictionAlgorithmConfig =
evictionConfig.getDefaultEvictionRegionConfig().
+ getEvictionAlgorithmConfig();
+
+ if (evictionAlgorithmConfig instanceof EvictionAlgorithmConfigBase) {
+ EvictionAlgorithmConfigBase baseEvicitonConfig =
(EvictionAlgorithmConfigBase) evictionAlgorithmConfig;
+ if (baseEvicitonConfig.getMaxNodes() <= 0) {
+ int maxCacheSize =
ContextInitParameters.getResourcesCacheSize(facesContext);
+ LOG.info(MessageFormat.format("Maximum cache size hasn''t
been set, resetting to {0} max items", maxCacheSize));
+ baseEvicitonConfig.setMaxNodes(maxCacheSize);
+ }
+ }
+ }
+
+ public org.ajax4jsf.cache.Cache createCache(FacesContext facesContext, String
cacheName, Map<?, ?> env) {
+ //TODO - handle cache name
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
Cache<String, Object> cache = null;
URL cacheConfigurationURL = null;
if (contextClassLoader != null) {
- cacheConfigurationURL =
contextClassLoader.getResource("/jboss-cache.xml");
+ cacheConfigurationURL =
contextClassLoader.getResource("jboss-cache.xml");
}
if (cacheConfigurationURL != null) {
@@ -47,6 +72,7 @@
try {
stream = URLToStreamHelper.urlToStream(cacheConfigurationURL);
cache = cacheFactory.createCache(stream);
+ setupMaxSizeEviction(facesContext, cache);
} catch (IOException e) {
throw new FacesException(e.getLocalizedMessage(), e);
} finally {
@@ -64,7 +90,8 @@
Configuration configuration = new Configuration();
EvictionRegionConfig evictionRegionConfig = new
EvictionRegionConfig(Fqn.root());
ExpirationAlgorithmConfig expirationAlgorithm = new
ExpirationAlgorithmConfig();
-
+
expirationAlgorithm.setMaxNodes(ContextInitParameters.getResourcesCacheSize(facesContext));
+
evictionRegionConfig.setEvictionAlgorithmConfig(expirationAlgorithm);
EvictionConfig evictionConfig = new EvictionConfig(evictionRegionConfig);
@@ -73,7 +100,11 @@
configuration.setEvictionConfig(evictionConfig);
cache = cacheFactory.createCache(configuration);
}
-
+
return new JBossCacheCache(cache);
}
+
+ public void destroy() {
+ cacheFactory = null;
+ }
}
Modified: root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -21,24 +21,35 @@
package org.ajax4jsf.cache;
-import com.opensymphony.oscache.general.GeneralCacheAdministrator;
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.text.MessageFormat;
+import java.util.ArrayList;
+import java.util.List;
import java.util.Map;
import java.util.Properties;
+import javax.faces.context.FacesContext;
+
+import org.ajax4jsf.context.ContextInitParameters;
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+import org.richfaces.log.RichfacesLogger;
+import org.slf4j.Logger;
+
+import com.opensymphony.oscache.base.AbstractCacheAdministrator;
+import com.opensymphony.oscache.general.GeneralCacheAdministrator;
+
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 01.05.2007
*/
public class OSCacheCacheFactory implements CacheFactory {
+
private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
+ private List<GeneralCacheAdministrator> cacheAdministrators = new
ArrayList<GeneralCacheAdministrator>(1);
+
private static Properties loadProperties() throws IOException {
Properties properties = new Properties();
URL resource = OSCacheCache.class.getResource("oscache.properties");
@@ -61,7 +72,8 @@
return properties;
}
- public Cache createCache(Map<?, ?> env) {
+ public Cache createCache(FacesContext facesContext, String cacheName, Map<?, ?>
env) {
+ //TODO - handle cache name
Properties cacheProperties = new Properties();
try {
@@ -83,8 +95,24 @@
cacheProperties.putAll(env);
LOG.info("Creating OSCache cache instance using parameters: " +
cacheProperties);
+ String property =
cacheProperties.getProperty(AbstractCacheAdministrator.CACHE_CAPACITY_KEY);
+ if (property == null) {
+ int maxCacheSize =
ContextInitParameters.getResourcesCacheSize(facesContext);
+ LOG.info(MessageFormat.format("Maximum cache size hasn''t been
set, resetting to {0} max items", maxCacheSize));
+ cacheProperties.put(AbstractCacheAdministrator.CACHE_CAPACITY_KEY,
+ Integer.toString(maxCacheSize));
+ }
+
GeneralCacheAdministrator cacheAdministrator = new
GeneralCacheAdministrator(cacheProperties);
-
+ cacheAdministrators.add(cacheAdministrator);
return new OSCacheCache(cacheAdministrator.getCache());
}
+
+ public void destroy() {
+ for (GeneralCacheAdministrator cacheAdministrator : cacheAdministrators) {
+ cacheAdministrator.destroy();
+ }
+
+ cacheAdministrators = null;
+ }
}
Modified: root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
===================================================================
--- root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -108,6 +108,6 @@
@Override
public String toString() {
- return (expired == null) ? key.toString() : key + ": " + expired;
+ return "<CacheEntry> " + ((expired == null) ? key.toString() :
key + ": " + expired);
}
}
Modified:
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -21,13 +21,16 @@
package org.ajax4jsf.cache.lru;
+import java.util.Map;
+
+import javax.faces.context.FacesContext;
+
import org.ajax4jsf.cache.Cache;
import org.ajax4jsf.cache.CacheFactory;
+import org.ajax4jsf.context.ContextInitParameters;
import org.richfaces.log.RichfacesLogger;
import org.slf4j.Logger;
-import java.util.Map;
-
/**
* @author Nick - mailto:nbelaevski@exadel.com
* created 01.05.2007
@@ -36,21 +39,22 @@
public static final String CACHE_SIZE_PARAMETER =
"org.ajax4jsf.cache.LRU_MAP_CACHE_SIZE";
private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
- public Cache createCache(Map<?, ?> env) {
+ public Cache createCache(FacesContext facesContext, String cacheName, Map<?, ?>
env) {
+ //TODO - handle cache name
LOG.info("Creating LRUMap cache instance using parameters: " + env);
String size = (String) env.get(CACHE_SIZE_PARAMETER);
-
if ((size == null) || (size.length() == 0)) {
- LOG.info("Creating LRUMap cache instance of default capacity");
+ size =
Integer.toString(ContextInitParameters.getResourcesCacheSize(facesContext));
+ }
- return new LRUMapCache();
- } else {
- int parsedSize = Integer.parseInt(size);
+ int parsedSize = Integer.parseInt(size);
- LOG.info("Creating LRUMap cache instance of " + parsedSize + "
items capacity");
+ LOG.info("Creating LRUMap cache instance of " + parsedSize + "
items capacity");
- return new LRUMapCache(parsedSize);
- }
+ return new LRUMapCache(parsedSize);
}
+
+ public void destroy() {
+ }
}
Modified:
root/core/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/ajax4jsf/context/ContextInitParameters.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -57,8 +57,12 @@
public static final String[] QUEUE_ENABLED =
{"org.richfaces.queue.enabled"};
//TODO - better name
- public static final String[] RESOURCES_TTL =
{"org.richfaces.RESOURCE_DEFAULT_TTL"};
+ public static final String RESOURCES_TTL =
"org.richfaces.RESOURCE_DEFAULT_TTL";
+ public static final String RESOURCES_CACHE_SIZE =
"org.richfaces.RESOURCE_CACHE_SIZE";
+ private static final String[] RESOURCES_TTL_ARRAY = { RESOURCES_TTL };
+ private static final String[] RESOURCES_CACHE_SIZE_ARRAY = { RESOURCES_CACHE_SIZE };
+
private static final String INIT_PARAM_PREFIX =
ContextInitParameters.class.getSimpleName() + ":";
private static final Object NULL = new Object() {
@@ -104,9 +108,13 @@
}
public static int getResourcesTimeToLive(FacesContext context) {
- return getInteger(context, RESOURCES_TTL, DEFAULT_TTL);
+ return getInteger(context, RESOURCES_TTL_ARRAY, DEFAULT_TTL);
}
+ public static int getResourcesCacheSize(FacesContext context) {
+ return getInteger(context, RESOURCES_CACHE_SIZE_ARRAY, 512);
+ }
+
/**
* Method for determining STD_CONTROLS_SKINNING_CLASSES_PARAM parameter
*
Modified:
root/core/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/ajax4jsf/resource/InternetResourceService.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -21,16 +21,10 @@
package org.ajax4jsf.resource;
-import org.ajax4jsf.Messages;
-import org.ajax4jsf.cache.Cache;
-import org.ajax4jsf.cache.CacheFactory;
-import org.ajax4jsf.cache.CacheManager;
-import org.ajax4jsf.cache.ServletContextInitMap;
-import org.ajax4jsf.resource.util.URLToStreamHelper;
-import org.ajax4jsf.webapp.BaseFilter;
-import org.ajax4jsf.webapp.WebXml;
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Map;
+import java.util.Properties;
import javax.faces.FacesException;
import javax.faces.FactoryFinder;
@@ -43,11 +37,17 @@
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Map;
-import java.util.Properties;
+import org.ajax4jsf.Messages;
+import org.ajax4jsf.cache.Cache;
+import org.ajax4jsf.cache.CacheManager;
+import org.ajax4jsf.cache.ServletContextInitMap;
+import org.ajax4jsf.resource.util.URLToStreamHelper;
+import org.ajax4jsf.webapp.BaseFilter;
+import org.ajax4jsf.webapp.WebXml;
+import org.richfaces.log.RichfacesLogger;
+import org.slf4j.Logger;
+
public class InternetResourceService {
static final String ENABLE_CACHING_PARAMETER = "enable-cache";
private static final String RESOURCE_LIFECYCLE_PARAMETER =
"org.ajax4jsf.RESOURCE_LIFECYCLE";
@@ -85,11 +85,9 @@
// this.cacheAdmin = ServletCacheAdministrator.getInstance(
// servletContext, cacheProperties);
- CacheManager cacheManager = CacheManager.getInstance();
+ CacheManager cacheManager = new CacheManager();
Map<String, String> env = new ServletContextInitMap(servletContext);
- CacheFactory cacheFactory = cacheManager.getCacheFactory(env);
-
- this.cache = cacheFactory.createCache(env);
+ this.cache = cacheManager.createCache(FacesContext.getCurrentInstance(),
"org.richfaces.resources", env);
}
// Create Resource-specific Faces Lifecycle instance.
Modified: root/core/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java
===================================================================
--- root/core/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java 2010-06-11 17:44:40
UTC (rev 17618)
+++ root/core/trunk/impl/src/main/java/org/ajax4jsf/util/LRUMap.java 2010-06-12 22:25:33
UTC (rev 17619)
@@ -43,7 +43,7 @@
* Default capacity constructor
*/
public LRUMap() {
- this(100);
+ this(1000);
}
/**
Modified:
root/core/trunk/impl/src/main/java/org/richfaces/application/InitializationListener.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/richfaces/application/InitializationListener.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/richfaces/application/InitializationListener.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -28,6 +28,7 @@
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
+import java.util.Map;
import javax.faces.FacesException;
import javax.faces.context.FacesContext;
@@ -37,12 +38,14 @@
import javax.faces.event.SystemEvent;
import javax.faces.event.SystemEventListener;
+import org.ajax4jsf.cache.Cache;
import org.ajax4jsf.cache.CacheManager;
import org.ajax4jsf.renderkit.AJAXDataSerializer;
import org.ajax4jsf.resource.util.URLToStreamHelper;
import org.richfaces.log.RichfacesLogger;
import org.richfaces.resource.DefaultResourceCodec;
import org.richfaces.resource.ResourceCodec;
+import org.richfaces.resource.ResourceHandlerImpl;
import org.richfaces.skin.SkinFactory;
import org.richfaces.skin.SkinFactoryImpl;
import org.slf4j.Logger;
@@ -57,6 +60,8 @@
private static final Logger LOG = RichfacesLogger.APPLICATION.getLogger();
+ private static final String CACHE_MANAGER_ATTRIBUTE_NAME =
InitializationListener.class.getName() + ":CacheManager";
+
/* (non-Javadoc)
* @see javax.faces.event.SystemEventListener#isListenerForSource(java.lang.Object)
*/
@@ -150,6 +155,19 @@
return instantiate(interfaceClass, implementationClass,
defaultImplementationClass);
}
+ private CacheManager createAndStoreCacheManager(FacesContext context) {
+ CacheManager cacheManager = new CacheManager();
+ Map<String, Object> applicationMap =
context.getExternalContext().getApplicationMap();
+ applicationMap.put(CACHE_MANAGER_ATTRIBUTE_NAME, cacheManager);
+
+ return cacheManager;
+ }
+
+ private CacheManager getStoredCacheManager(FacesContext context) {
+ Map<String, Object> applicationMap =
context.getExternalContext().getApplicationMap();
+ return (CacheManager) applicationMap.get(CACHE_MANAGER_ATTRIBUTE_NAME);
+ }
+
protected void onStart() {
FacesContext facesContext = FacesContext.getCurrentInstance();
@@ -165,13 +183,21 @@
ResourceCodec resourceCodec = createServiceInstance(ResourceCodec.class,
DefaultResourceCodec.class);
ServiceTracker.setService(facesContext, ResourceCodec.class, resourceCodec);
+
+ CacheManager cacheManager = createAndStoreCacheManager(facesContext);
+
+ Map<?, ?> envMap =
facesContext.getExternalContext().getInitParameterMap();
+ Cache cache = cacheManager.createCache(facesContext,
ResourceHandlerImpl.RESOURCE_CACHE_NAME, envMap);
+ ServiceTracker.setService(facesContext, Cache.class, cache);
}
protected void onStop() {
FacesContext facesContext = FacesContext.getCurrentInstance();
+ CacheManager cacheManager = getStoredCacheManager(facesContext);
+ cacheManager.destroy();
+
ServiceTracker.release(facesContext);
- CacheManager.getInstance().destroy();
}
/* (non-Javadoc)
Modified:
root/core/trunk/impl/src/main/java/org/richfaces/application/ServiceTrackerLockPhaseListener.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/richfaces/application/ServiceTrackerLockPhaseListener.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/richfaces/application/ServiceTrackerLockPhaseListener.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -27,8 +27,11 @@
import javax.faces.lifecycle.Lifecycle;
/**
+ * As service tracker is filled by application startup listeners,
+ * we can't rely on some "locking" system listener that's the last in
chain,
+ * so PhaseListener does the job.
+ *
* @author Nick Belaevski
- *
*/
public class ServiceTrackerLockPhaseListener implements PhaseListener {
Modified:
root/core/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java
===================================================================
---
root/core/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -44,7 +44,6 @@
import javax.servlet.http.HttpServletResponse;
import org.ajax4jsf.cache.Cache;
-import org.ajax4jsf.cache.CacheManager;
import org.richfaces.application.DependencyInjectionService;
import org.richfaces.application.ServiceTracker;
import org.richfaces.log.RichfacesLogger;
@@ -58,7 +57,7 @@
*/
public class ResourceHandlerImpl extends ResourceHandlerWrapper {
public static final String RICHFACES_RESOURCE_IDENTIFIER = "/rfRes/";
- public static final String RESOURCE_CACHE_NAME = ResourceHandlerImpl.class.getName()
+ ":CACHE";
+ public static final String RESOURCE_CACHE_NAME =
"org.richfaces.ResourcesCache";
public static final String HANDLER_START_TIME_ATTRIBUTE =
ResourceHandlerImpl.class.getName() + ":StartTime";
private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
@@ -80,7 +79,6 @@
}
}
- private Cache cache;
private ResourceHandler defaultHandler;
public ResourceHandlerImpl(ResourceHandler defaultHandler) {
@@ -89,18 +87,8 @@
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format("Instance of {0} resource handler
created", getClass().getName()));
}
-
- FacesContext facesContext = FacesContext.getCurrentInstance();
-
- initializeCache(facesContext);
}
- private void initializeCache(FacesContext facesContext) {
- Map<?, ?> envMap =
facesContext.getExternalContext().getInitParameterMap();
-
- cache = CacheManager.getInstance().getNewCache(RESOURCE_CACHE_NAME, envMap);
- }
-
protected static String getResourcePathFromRequest(FacesContext context) {
String resourceName = Util.decodeResourceURL(context);
@@ -139,7 +127,7 @@
return isThisHandlerResourceRequest(context) ||
defaultHandler.isResourceRequest(context);
}
- private Resource lookupInCache(FacesContext context, String resourceKey) {
+ private Resource lookupInCache(Cache cache, String resourceKey) {
Resource resource = (Resource) cache.get(resourceKey);
if (LOGGER.isDebugEnabled()) {
@@ -163,7 +151,7 @@
}
private void logResourceProblem(FacesContext context, Throwable throwable, String
messagePattern,
- Object... arguments) {
+ Object... arguments) {
boolean isProductionStage = context.isProjectStage(ProjectStage.Production);
if (LOGGER.isWarnEnabled() || (!isProductionStage &&
LOGGER.isInfoEnabled())) {
@@ -195,14 +183,15 @@
ResourceCodec resourceCodec = ServiceTracker.getService(context,
ResourceCodec.class);
String resourcePath = getResourcePathFromRequest(context);
-
+
assert (resourcePath != null) && (resourcePath.length() != 0);
String resourceKey = resourceCodec.getResourceKey(context, resourcePath);
assert (resourceKey != null) && (resourceKey.length() != 0);
- Resource resource = lookupInCache(context, resourceKey);
+ Cache cache = ServiceTracker.getService(context, Cache.class);
+ Resource resource = lookupInCache(cache, resourceKey);
if (resource == null) {
String resourceName = resourceCodec.decodeResourceName(context,
resourcePath);
@@ -221,7 +210,7 @@
if (resource == null) {
resource = createHandlerDependentResource(resourceName, null);
}
-
+
if (resource == null) {
logMissingResource(context, resourceName);
sendResourceNotFound(context);
@@ -236,15 +225,15 @@
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(
- MessageFormat.format(
- "Client requested {0} version of resource,
server has {1} version",
- String.valueOf(requestedVersion),
String.valueOf(existingVersion)));
+ MessageFormat.format(
+ "Client requested {0} version of resource, server
has {1} version",
+ String.valueOf(requestedVersion),
String.valueOf(existingVersion)));
}
if ((existingVersion != null) && (requestedVersion != null)
- && !existingVersion.equals(requestedVersion)) {
+ && !existingVersion.equals(requestedVersion)) {
logResourceProblem(context, null, "Resource {0} of version
{1} was not found", resourceName,
- requestedVersion);
+ requestedVersion);
sendResourceNotFound(context);
return;
@@ -296,15 +285,15 @@
// someone may provided this resource for us
// while we were reading it, check once again
- resource = lookupInCache(context, resourceKey);
+ resource = lookupInCache(cache, resourceKey);
if (resource == null) {
Date cacheExpirationDate =
cachedResource.getExpired(context);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(new MessageFormat(
- "Storing {0} resource in cache until
{1,date,dd MMM yyyy HH:mm:ss zzz}", Locale.US).
- format(new Object[]{resourceKey,
cacheExpirationDate}));
+ "Storing {0} resource in cache until {1,date,dd
MMM yyyy HH:mm:ss zzz}", Locale.US).
+ format(new Object[]{resourceKey,
cacheExpirationDate}));
}
cache.put(resourceKey, cachedResource, cacheExpirationDate);
@@ -392,7 +381,7 @@
protected void injectProperties(Object resource, Map<String, String>
parameters) {
FacesContext facesContext = FacesContext.getCurrentInstance();
DependencyInjectionService diService = ServiceTracker.getService(facesContext,
DependencyInjectionService.class);
-
+
Map<Object, Object> attributes = facesContext.getAttributes();
try {
attributes.put(ResourceParameterELResolver.CONTEXT_ATTRIBUTE_NAME,
parameters);
@@ -401,7 +390,7 @@
attributes.remove(ResourceParameterELResolver.CONTEXT_ATTRIBUTE_NAME);
}
}
-
+
/**
* Should be called only if {@link #isResourceExists(String)} returns
<code>true</code>
*
@@ -415,9 +404,9 @@
if (contextClassLoader != null) {
try {
Class<?> loadedClass = Class.forName(resourceName, false,
contextClassLoader);
-
+
boolean legitimateResource = false;
-
+
DynamicResource annotation =
loadedClass.getAnnotation(DynamicResource.class);
legitimateResource = (annotation != null);
if (legitimateResource) {
@@ -427,7 +416,7 @@
LOGGER.debug(
MessageFormat.format("Dynamic resource annotation is not
present on resource class {0}", resourceName));
}
-
+
if (!legitimateResource) {
// TODO resource marker extension name?
URL resourceMarkerUrl =
contextClassLoader.getResource("META-INF/" + resourceName +
".resource.properties");
@@ -444,7 +433,7 @@
}
}
}
-
+
if (legitimateResource) {
Object wrappedResource;
if (Java2DUserResource.class.isAssignableFrom(loadedClass)) {
@@ -460,15 +449,15 @@
resource = (Resource) resourceClass.newInstance();
wrappedResource = resource;
}
-
+
if (parameters != null) {
injectProperties(wrappedResource, parameters);
}
-
+
resource.setResourceName(resourceName);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug(MessageFormat.format("Successfully created
instance of {0} resource",
- resourceName));
+ resourceName));
}
}
} catch (ClassNotFoundException e) {
@@ -494,7 +483,7 @@
if ((resourceName != null) && ((libraryName == null) ||
(libraryName.length() == 0))) {
result = createHandlerDependentResource(resourceName, params);
}
-
+
if (result == null) {
result = defaultHandler.createResource(resourceName, libraryName,
contentType);
}
Modified: root/core/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java
===================================================================
--- root/core/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/main/java/org/richfaces/skin/BasicSkinImpl.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -21,15 +21,19 @@
package org.richfaces.skin;
-import javax.el.ValueExpression;
-import javax.faces.context.ExternalContext;
-import javax.faces.context.FacesContext;
+import java.awt.Color;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
+import javax.el.ValueExpression;
+import javax.faces.context.ExternalContext;
+import javax.faces.context.FacesContext;
+
+import org.ajax4jsf.util.HtmlColor;
+
/**
* Singleton ( in respect as collection of different skins ) for produce
* instances properties for all used skins.
@@ -85,6 +89,29 @@
return value;
}
+ protected Integer decodeColor(Object value) {
+ if (value instanceof Color) {
+ return ((Color) value).getRGB();
+ } else if (value instanceof Integer) {
+ return ((Integer) value).intValue();
+ } else {
+ String stringValue = (String) value;
+ if (stringValue != null && stringValue.length() != 0) {
+ return Integer.valueOf(HtmlColor.decode(stringValue).getRGB());
+ } else {
+ return null;
+ }
+ }
+ }
+
+ public Integer getColorParameter(FacesContext context, String name) {
+ return decodeColor(getParameter(context, name));
+ }
+
+ public Integer getColorParameter(FacesContext context, String name, Object
defaultValue) {
+ return decodeColor(getParameter(context, name, defaultValue));
+ }
+
protected Object getLocalParameter(FacesContext context, String name) {
return getValueReference(context, skinParams.get(name));
}
Modified: root/core/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java
===================================================================
--- root/core/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/main/java/org/richfaces/skin/SkinBean.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -21,12 +21,13 @@
package org.richfaces.skin;
-import javax.faces.context.FacesContext;
import java.nio.ByteBuffer;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Set;
+import javax.faces.context.FacesContext;
+
/**
* @author shura (latest modification by $Author: alexsmirnov $)
* @version $Revision: 1.1.2.1 $ $Date: 2007/01/09 18:59:40 $
@@ -142,4 +143,18 @@
return bs;
}
+
+ /* (non-Javadoc)
+ * @see org.richfaces.skin.Skin#getColorParameter(javax.faces.context.FacesContext,
java.lang.String)
+ */
+ public Integer getColorParameter(FacesContext context, String name) {
+ return getSkin().getColorParameter(context, name);
+ }
+
+ /* (non-Javadoc)
+ * @see org.richfaces.skin.Skin#getColorParameter(javax.faces.context.FacesContext,
java.lang.String, java.lang.Object)
+ */
+ public Integer getColorParameter(FacesContext context, String name, Object
defaultValue) {
+ return getSkin().getColorParameter(context, name, defaultValue);
+ }
}
Added:
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/ehcache-failsafe-richfaces.xml
===================================================================
---
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/ehcache-failsafe-richfaces.xml
(rev 0)
+++
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/ehcache-failsafe-richfaces.xml 2010-06-12
22:25:33 UTC (rev 17619)
@@ -0,0 +1,26 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<ehcache
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
+ updateCheck="true" monitoring="off"
dynamicConfig="true">
+
+ <diskStore path="java.io.tmpdir"/>
+
+ <!--
+ Mandatory Default Cache configuration. These settings will be
+ applied to caches created programmtically using
+ CacheManager.add(String cacheName). The defaultCache has an
+ implicit name "default" which is a reserved cache name.
+ -->
+ <defaultCache
+ maxElementsInMemory="10000"
+ eternal="false"
+ timeToIdleSeconds="120"
+ timeToLiveSeconds="120"
+ overflowToDisk="true"
+ maxElementsOnDisk="10000000"
+ diskPersistent="false"
+ diskExpiryThreadIntervalSeconds="120"
+ memoryStoreEvictionPolicy="LRU"
+ />
+</ehcache>
\ No newline at end of file
Modified: root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/oscache.properties
===================================================================
---
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/oscache.properties 2010-06-11
17:44:40 UTC (rev 17618)
+++
root/core/trunk/impl/src/main/resources/org/ajax4jsf/cache/oscache.properties 2010-06-12
22:25:33 UTC (rev 17619)
@@ -1,7 +1,7 @@
cache.memory = true
-cache.capacity = 10000
+#cache.capacity = 1000
cache.use.host.domain.in.key = true
-
+cache.blocking = true
# CACHE IN MEMORY
#
# If you want to disable memory caching, just uncomment this line.
@@ -104,9 +104,8 @@
# Default cache size in number of items. If a size is specified but not
# an algorithm, the cache algorithm used will be LRUCache.
#
-cache.capacity=1000
+# cache.capacity=1000
-
# CACHE UNLIMITED DISK
# Use unlimited disk cache or not. The default value is false, which means
# the disk cache will be limited in size to the value specified by cache.capacity.
Modified: root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java
===================================================================
--- root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/BaseCacheTest.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -24,15 +24,24 @@
package org.ajax4jsf.cache;
import java.util.Date;
+import java.util.LinkedHashMap;
import java.util.Map;
+import java.util.UUID;
+import java.util.concurrent.atomic.AtomicBoolean;
+import org.ajax4jsf.context.ContextInitParameters;
import org.jboss.test.faces.AbstractFacesTest;
+import org.junit.Assert;
/**
* @author Nick Belaevski
* @since 4.0
*/
public abstract class BaseCacheTest extends AbstractFacesTest {
+
+ private int sizeLimit;
+
+ private CacheManager cacheManager;
private Cache cache;
private String cacheManagerFactoryClassName;
@@ -45,17 +54,26 @@
protected void setupJsfInitParameters() {
super.setupJsfInitParameters();
this.facesServer.addInitParameter(CacheManager.CACHE_MANAGER_FACTORY_CLASS,
cacheManagerFactoryClassName);
+ this.facesServer.addInitParameter(ContextInitParameters.RESOURCES_CACHE_SIZE,
Integer.toString(sizeLimit));
}
+ protected Cache getCache() {
+ return cache;
+ }
+
@Override
public void setUp() throws Exception {
+ sizeLimit = 64;
+
super.setUp();
+
setupFacesRequest();
- CacheManager cacheManager = CacheManager.getInstance();
+ cacheManager = new CacheManager();
+
Map<?, ?> initParameterMap =
facesContext.getExternalContext().getInitParameterMap();
- this.cache =
cacheManager.getCacheFactory(initParameterMap).createCache(initParameterMap);
+ this.cache = cacheManager.createCache(facesContext, "test-cache",
initParameterMap);
this.cache.start();
}
@@ -63,10 +81,7 @@
public void tearDown() throws Exception {
super.tearDown();
- if (this.cache != null) {
- this.cache.stop();
- this.cache = null;
- }
+ cacheManager.destroy();
}
public void testBasic() throws Exception {
@@ -84,6 +99,8 @@
cache.put("a", "value-a", new Date(expirationTime));
assertEquals("value-a", cache.get("a"));
+ cache.put("b", "value-b", new Date(expirationTime));
+ assertEquals("value-b", cache.get("b"));
// interval to reach 1 second before expiration time
sleepTime = expirationTime - 1000 - System.currentTimeMillis();
assertTrue(sleepTime > 0);
@@ -96,4 +113,115 @@
Thread.sleep(sleepTime);
assertNull(cache.get("a"));
}
+
+ public void testMaxSize() throws Exception {
+ Date expirationDate = new Date(System.currentTimeMillis() +
+ 3600000 /* one hour - this should be enough for our test */);
+
+ Map<String, String> data = new LinkedHashMap<String, String>();
+ for (int i = 0; i < sizeLimit; i++) {
+ String key = UUID.randomUUID().toString();
+ String value = UUID.randomUUID().toString();
+ data.put(key, value);
+ cache.put(key, value, expirationDate);
+ }
+
+ for (Map.Entry<String, String> entry : data.entrySet()) {
+ String key = entry.getKey();
+
+ Object cacheValue = cache.get(key);
+ assertEquals(entry.getValue(), cacheValue);
+ }
+
+ String extraEntryKey = UUID.randomUUID().toString();
+ String extraEntryValue = UUID.randomUUID().toString();
+ data.put(extraEntryKey, extraEntryValue);
+ cache.put(extraEntryKey, extraEntryValue, expirationDate);
+
+ //give cache time to evict
+ Thread.sleep(2000);
+
+ int nullCounter = 0;
+ for (Map.Entry<String, String> entry : data.entrySet()) {
+ String key = entry.getKey();
+
+ Object cacheValue = cache.get(key);
+ if (cacheValue == null) {
+ nullCounter++;
+ } else {
+ assertEquals(entry.getValue(), cacheValue);
+ }
+ }
+
+ assertTrue(nullCounter == 1);
+ }
+
+ public void testThreads() throws Exception {
+ final AtomicBoolean failure = new AtomicBoolean();
+
+ Thread[] writerThreads = new Thread[10];
+
+ for (int i = 0; i < writerThreads.length; i++) {
+ writerThreads[i] = new Thread() {
+ public void run() {
+ final String key = UUID.randomUUID().toString();
+ final String value = UUID.randomUUID().toString();
+
+ cache.put(key, value, null);
+
+ Thread[] threads = new Thread[25];
+
+ for (int j = 0; j < threads.length; j++) {
+ threads[j] = new Thread() {
+ @Override
+ public void run() {
+ int retries = 1000;
+
+ for (int k = 0; k < retries; k++) {
+ if (!value.equals(cache.get(key))) {
+ failure.set(true);
+
+ return;
+ }
+ }
+ }
+ };
+ }
+
+ for (Thread thread : threads) {
+ thread.start();
+ }
+
+ int retries = 1000;
+
+ for (int k = 0; k < retries; k++) {
+ if (!value.equals(cache.get(key))) {
+ failure.set(true);
+ }
+ }
+
+ for (Thread thread : threads) {
+ try {
+ thread.join();
+ } catch (InterruptedException e) {
+
+ // TODO Auto-generated catch block
+ failure.set(true);
+ }
+ }
+ }
+ ;
+ };
+ }
+
+ for (Thread thread : writerThreads) {
+ thread.start();
+ }
+
+ for (Thread thread : writerThreads) {
+ thread.join();
+ }
+
+ Assert.assertFalse(failure.get());
+ }
}
Modified: root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java
===================================================================
--- root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java 2010-06-11
17:44:40 UTC (rev 17618)
+++ root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -23,182 +23,16 @@
package org.ajax4jsf.cache;
-import java.util.Date;
-import java.util.UUID;
-import java.util.concurrent.atomic.AtomicBoolean;
+import org.ajax4jsf.cache.lru.LRUMapCacheFactory;
-import org.ajax4jsf.cache.lru.CacheEntry;
-import org.ajax4jsf.cache.lru.CacheMap;
-import org.ajax4jsf.cache.lru.LRUMapCache;
-import org.junit.Assert;
-import org.junit.Test;
-
/**
* @author Nick Belaevski
* @since 4.0
*/
-public class LRUMapCacheTest {
- @Test
- public void testBasic() throws Exception {
- LRUMapCache cache = new LRUMapCache();
+public class LRUMapCacheTest extends BaseCacheTest {
- cache.start();
- Assert.assertNull(cache.get("key"));
- cache.put("key", "value", null);
- Assert.assertEquals("value", cache.get("key"));
- cache.stop();
+ public LRUMapCacheTest() {
+ super(LRUMapCacheFactory.class.getName());
}
-
- @Test
- public void testLRUEviction() throws Exception {
- LRUMapCache cache = new LRUMapCache(3);
-
- cache.start();
- cache.put("key1", "value1", null);
- cache.put("key2", "value2", null);
- cache.put("key3", "value3", null);
- Assert.assertEquals("value1", cache.get("key1"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertEquals("value3", cache.get("key3"));
- cache.get("key1");
- cache.get("key3");
- cache.put("key4", "value4", null);
- Assert.assertEquals("value1", cache.get("key1"));
- Assert.assertNull(cache.get("key2"));
- Assert.assertEquals("value3", cache.get("key3"));
- Assert.assertEquals("value4", cache.get("key4"));
- cache.stop();
- }
-
- @Test
- public void testCacheMap() throws Exception {
- CacheMap cacheMap = new CacheMap();
-
- Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
-
- CacheEntry cacheEntry = new CacheEntry("key", "value", new
Date(System.currentTimeMillis() + 1000));
-
- cacheMap.put("key", cacheEntry);
- Assert.assertNotNull(cacheMap.get("key"));
- Assert.assertSame(cacheEntry, cacheMap.get("key"));
- Assert.assertFalse(cacheMap.getExpirationQueue().isEmpty());
- cacheMap.clear();
- Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
- cacheMap.put("key2", new CacheEntry("key2",
"value2", new Date(System.currentTimeMillis() + 1000)));
- Assert.assertNotNull(cacheMap.get("key2"));
- cacheMap.remove("key2");
- Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
- }
-
- @Test
- public void testExpiration() throws Exception {
-
- // this test uses Thread.sleep, so may fail if debugged
- LRUMapCache cache = new LRUMapCache();
-
- cache.start();
-
- long baseTime = System.currentTimeMillis();
-
- cache.put("key", "value", new Date(baseTime + 2000));
- cache.put("key2", "value2", new Date(baseTime + 3000));
- cache.put("key3", "value3", new Date(baseTime + 1000));
- cache.put("key4", "value4", new Date(baseTime + 1000));
- Assert.assertEquals("value", cache.get("key"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertEquals("value3", cache.get("key3"));
- Assert.assertEquals("value4", cache.get("key4"));
-
- // prolong key4
- cache.put("key4", "new value", new Date(baseTime + 2000));
- Thread.sleep(1500);
- Assert.assertEquals("value", cache.get("key"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertNull(cache.get("key3"));
- Assert.assertEquals("new value", cache.get("key4"));
- Thread.sleep(1000);
- Assert.assertNull(cache.get("key"));
- Assert.assertEquals("value2", cache.get("key2"));
- Assert.assertNull(cache.get("key3"));
- Assert.assertNull(cache.get("key4"));
- Thread.sleep(1000);
- Assert.assertNull(cache.get("key"));
- Assert.assertNull(cache.get("key2"));
- Assert.assertNull(cache.get("key3"));
- cache.stop();
- }
-
- @Test
- public void testThreads() throws Exception {
- final AtomicBoolean failure = new AtomicBoolean();
- final LRUMapCache cache = new LRUMapCache();
-
- cache.start();
-
- Thread[] writerThreads = new Thread[10];
-
- for (int i = 0; i < writerThreads.length; i++) {
- writerThreads[i] = new Thread() {
- public void run() {
- final String key = UUID.randomUUID().toString();
- final String value = UUID.randomUUID().toString();
-
- cache.put(key, value, null);
-
- Thread[] threads = new Thread[25];
-
- for (int j = 0; j < threads.length; j++) {
- threads[j] = new Thread() {
- @Override
- public void run() {
- int retries = 1000;
-
- for (int k = 0; k < retries; k++) {
- if (!value.equals(cache.get(key))) {
- failure.set(true);
-
- return;
- }
- }
- }
- };
- }
-
- for (Thread thread : threads) {
- thread.start();
- }
-
- int retries = 1000;
-
- for (int k = 0; k < retries; k++) {
- if (!value.equals(cache.get(key))) {
- failure.set(true);
- }
- }
-
- for (Thread thread : threads) {
- try {
- thread.join();
- } catch (InterruptedException e) {
-
- // TODO Auto-generated catch block
- failure.set(true);
- }
- }
- }
- ;
- };
- }
-
- for (Thread thread : writerThreads) {
- thread.start();
- }
-
- for (Thread thread : writerThreads) {
- thread.join();
- }
-
- Assert.assertFalse(failure.get());
- cache.stop();
- }
+
}
Added: root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/lru/CacheMapTest.java
===================================================================
--- root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/lru/CacheMapTest.java
(rev 0)
+++ root/core/trunk/impl/src/test/java/org/ajax4jsf/cache/lru/CacheMapTest.java 2010-06-12
22:25:33 UTC (rev 17619)
@@ -0,0 +1,76 @@
+/*
+ * JBoss, Home of Professional Open Source
+ * Copyright 2010, Red Hat, Inc. and individual contributors
+ * by the @authors tag. See the copyright.txt in the distribution for a
+ * full listing of individual contributors.
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site:
http://www.fsf.org.
+ */
+package org.ajax4jsf.cache.lru;
+
+import java.util.Date;
+
+import junit.framework.TestCase;
+
+import org.junit.Assert;
+
+
+/**
+ * @author Nick Belaevski
+ *
+ */
+public class CacheMapTest extends TestCase {
+
+ private void addToCacheMap(CacheMap cacheMap, String key, String value) {
+ CacheEntry entry = new CacheEntry(key, value, null);
+ cacheMap.put(key, entry);
+ }
+
+ public void testLRUEviction() throws Exception {
+ CacheMap cache = new CacheMap(3);
+ addToCacheMap(cache, "key1", "value1");
+ addToCacheMap(cache, "key2", "value2");
+ addToCacheMap(cache, "key3", "value3");
+ Assert.assertEquals("value1", cache.get("key1").getValue());
+ Assert.assertEquals("value2", cache.get("key2").getValue());
+ Assert.assertEquals("value3", cache.get("key3").getValue());
+ cache.get("key1");
+ cache.get("key3");
+ addToCacheMap(cache, "key4", "value4");
+ Assert.assertEquals("value1", cache.get("key1").getValue());
+ Assert.assertNull(cache.get("key2"));
+ Assert.assertEquals("value3", cache.get("key3").getValue());
+ Assert.assertEquals("value4", cache.get("key4").getValue());
+ }
+
+ public void testExpirationQueue() throws Exception {
+ CacheMap cacheMap = new CacheMap();
+
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
+
+ CacheEntry cacheEntry = new CacheEntry("key", "value", new
Date(System.currentTimeMillis() + 1000));
+ cacheMap.put("key", cacheEntry);
+ Assert.assertNotNull(cacheMap.get("key"));
+ Assert.assertSame(cacheEntry, cacheMap.get("key"));
+ Assert.assertFalse(cacheMap.getExpirationQueue().isEmpty());
+ cacheMap.clear();
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
+ cacheMap.put("key2", new CacheEntry("key2",
"value2", new Date(System.currentTimeMillis() + 1000)));
+ Assert.assertNotNull(cacheMap.get("key2"));
+ cacheMap.remove("key2");
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
+ }
+}
Deleted: root/core/trunk/impl/src/test/resources/oscache.properties
===================================================================
--- root/core/trunk/impl/src/test/resources/oscache.properties 2010-06-11 17:44:40 UTC
(rev 17618)
+++ root/core/trunk/impl/src/test/resources/oscache.properties 2010-06-12 22:25:33 UTC
(rev 17619)
@@ -1,2 +0,0 @@
-cache.memory true
-cache.capacity 15
\ No newline at end of file