Author: Alex.Kolonitsky
Date: 2009-10-22 03:22:02 -0400 (Thu, 22 Oct 2009)
New Revision: 15745
Added:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java
Removed:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCache.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCacheFactory.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource.java
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java
root/framework/trunk/impl/src/main/java/org/richfaces/VersionBean.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java
root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java
root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java
Log:
Code review for A1 server-side code base
https://jira.jboss.org/jira/browse/RFPL-107
Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/CacheManager.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -28,30 +28,31 @@
import java.util.Properties;
import org.ajax4jsf.resource.util.URLToStreamHelper;
+import org.ajax4jsf.cache.lru.LRUMapCacheFactory;
import org.richfaces.log.RichfacesLogger;
import org.slf4j.Logger;
/**
+ * TODO stop caches on application stop
* CacheManager is used in J2SE environments for looking up named caches.
*/
-//TODO stop caches on application stop
public class CacheManager {
-
- private static final Logger log = RichfacesLogger.CACHE.getLogger();
+ private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
+
private static final String FACTORY_PROPERTY_NAME =
"org.ajax4jsf.cache.CacheFactory";
- public static final String CACHE_MANAGER_FACTORY_CLASS =
"org.ajax4jsf.cache.CACHE_MANAGER_FACTORY_CLASS";
+ public static final String CACHE_MANAGER_FACTORY_CLASS =
"org.ajax4jsf.cache.CACHE_MANAGER_FACTORY_CLASS";
- private static final String[] DEFAULT_FACTORIES_CHAIN = {
- "org.ajax4jsf.cache.JBossCacheCacheFactory",
"org.ajax4jsf.cache.EhCacheCacheFactory"
- };
+ private static final String[] DEFAULT_FACTORIES_CHAIN = {
+ "org.ajax4jsf.cache.JBossCacheCacheFactory",
"org.ajax4jsf.cache.EhCacheCacheFactory"
+ };
- protected static CacheManager instance = new CacheManager();
+ 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 final Map<String, Cache> caches = Collections.synchronizedMap(new
HashMap<String, Cache>());
+
/**
* Returns the singleton CacheManager
*/
@@ -63,31 +64,36 @@
return caches.get(cacheName);
}
+ public Cache getNewCache(String cacheName, Map<?, ?> env) {
+ createCache(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();
+
+ public void createCache(String cacheName, Map<?, ?> env) {
+ CacheFactory factory = getCacheFactory(env);
+ Cache cache = factory.createCache(env);
+ registerCache(cacheName, cache);
+ cache.start();
}
-
+
public void destroyCache(String cacheName) {
- Cache cache = caches.remove(cacheName);
- cache.stop();
+ Cache cache = caches.remove(cacheName);
+ cache.stop();
}
-
- public CacheFactory getCacheFactory(Map <?,?> env ) {
+
+ public CacheFactory getCacheFactory(Map<?, ?> env) {
String[] factories;
-
- String configuredFactoryName = findFactory(FACTORY_PROPERTY_NAME, env);
+
+ String configuredFactoryName = findFactory(FACTORY_PROPERTY_NAME, env);
if (configuredFactoryName != null) {
- log.info("Configured to use [" + configuredFactoryName + "]
cache factory");
- factories = new String[] {configuredFactoryName};
+ LOG.info("Configured to use [{0}] cache factory",
configuredFactoryName);
+ factories = new String[]{configuredFactoryName};
} else {
- factories = DEFAULT_FACTORIES_CHAIN;
+ factories = DEFAULT_FACTORIES_CHAIN;
}
ClassLoader loader = findClassLoader();
@@ -95,83 +101,118 @@
try {
Class<?> spiClass = Class.forName(factoryName, true, loader);
CacheFactory cacheFactory =
CacheFactory.class.cast(spiClass.newInstance());
-
- log.info("Selected [" + factoryName + "]");
-
+
+ LOG.info("Selected [{0}]", factoryName);
+
return cacheFactory;
} catch (Throwable iae) {
- //TODO log debug
+ //TODO LOG debug
}
- }
-
- log.info("Selected fallback cache factory");
+ }
+
+ LOG.info("Selected fallback cache factory");
return new LRUMapCacheFactory();
}
- public Map <String, Cache> getCaches() {
- return caches;
- }
+ public Map<String, Cache> getCaches() {
+ return caches;
+ }
- private ClassLoader findClassLoader() {
+ private ClassLoader findClassLoader() {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
- if (cl == null) cl = ClassLoader.getSystemClassLoader();
+ if (cl == null) {
+ cl = ClassLoader.getSystemClassLoader();
+ }
return cl;
}
- private boolean isEmptyString(String s) {
+ private static boolean isEmptyString(String s) {
return s == null || "".equals(s);
}
String findFactory(String factoryId, Map<?, ?> env) {
String envFactoryClass = (String) env.get(CACHE_MANAGER_FACTORY_CLASS);
- if (!isEmptyString(envFactoryClass)) return envFactoryClass;
-
+ if (!isEmptyString(envFactoryClass)) {
+ return envFactoryClass;
+ }
+
// Use the system property first
- try {
- String factoryClass = System.getProperty(factoryId);
- if (!isEmptyString(factoryClass)) return factoryClass;
- } catch (SecurityException ignore) {
+ String systemPropertyFactoryClass = searchInSystemProperty(factoryId);
+ if (!isEmptyString(systemPropertyFactoryClass)) {
+ return systemPropertyFactoryClass;
}
// try to read from $java.home/lib/jcache.properties
- try {
- String configFile = System.getProperty("java.home") +
- File.separator + "lib" + File.separator +
"jcache.properties";
- File f = new File(configFile);
- if (f.exists()) {
- InputStream in = new FileInputStream(f);
- try {
- Properties props = new Properties();
- props.load(in);
- String factoryClass = props.getProperty(factoryId);
- if (!isEmptyString(factoryClass)) return factoryClass;
- } finally {
- in.close();
- }
- }
- } catch (SecurityException ignore) {
- } catch (IOException ignore) {
+ String jcacheFactoryClass = searchInJcacheProperties(factoryId);
+ if (!isEmptyString(jcacheFactoryClass)) {
+ return jcacheFactoryClass;
}
// try to find services in CLASSPATH
+ String classpathFactoryClass = searchInClasspath(factoryId);
+ if (!isEmptyString(classpathFactoryClass)) {
+ return classpathFactoryClass;
+ }
+
+ return null;
+ }
+
+ private String searchInClasspath(String factoryId) {
try {
ClassLoader cl = findClassLoader();
InputStream is = URLToStreamHelper.urlToStreamSafe(
- cl.getResource("META-INF/services/" + factoryId));
+ cl.getResource("META-INF/services/" + factoryId));
if (is != null) {
BufferedReader r = new BufferedReader(new InputStreamReader(is,
"UTF-8"));
try {
- String factoryName = r.readLine();
- if (!isEmptyString(factoryName)) return factoryName;
+ return r.readLine();
} finally {
r.close();
}
}
} catch (IOException ignore) {
}
+ return null;
+ }
+ private static String searchInJcacheProperties(String factoryId) {
+ try {
+ String configFile = System.getProperty("java.home") +
+ File.separator + "lib" + File.separator +
"jcache.properties";
+ File file = new File(configFile);
+ if (file.exists()) {
+ InputStream in = new FileInputStream(file);
+ try {
+ Properties props = new Properties();
+ props.load(in);
+ return props.getProperty(factoryId);
+ } finally {
+ in.close();
+ }
+ }
+ } catch (SecurityException ignore) {
+ } catch (IOException ignore) {
+ }
+
return null;
}
-
+
+ private static String searchInSystemProperty(String factoryId) {
+ try {
+ return System.getProperty(factoryId);
+ } catch (SecurityException ignore) {
+ }
+ return null;
+ }
+
+ public void destroy() {
+ if (caches.isEmpty()) {
+ return;
+ }
+
+ for (String cacheName : caches.keySet()) {
+ destroyCache(cacheName);
+ }
+ }
}
Modified: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCache.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -41,7 +41,7 @@
}
public void put(Object key, Object value, Date expired) {
- Boolean eternal = null;/* use cache defaults */;
+ Boolean eternal = null; // use cache defaults
Integer ttl = null;
if (expired != null) {
eternal = Boolean.FALSE;
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/EhCacheCacheFactory.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -1,5 +1,5 @@
/**
- *
+ *
*/
package org.ajax4jsf.cache;
@@ -14,13 +14,13 @@
*/
public class EhCacheCacheFactory implements CacheFactory {
- private static final Logger log = RichfacesLogger.CACHE.getLogger();
+ private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
public Cache createCache(Map<?, ?> env) {
- log.info("Creating EhCache cache instance");
+ LOG.info("Creating EhCache cache instance");
- net.sf.ehcache.Ehcache cache = new net.sf.ehcache.Cache("org.richfaces",
256, false, true, 0, 0);
- return new EhCacheCache(cache);
- }
+ net.sf.ehcache.Ehcache cache = new
net.sf.ehcache.Cache("org.richfaces", 256, false, true, 0, 0);
+ return new EhCacheCache(cache);
+ }
}
Deleted: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCache.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCache.java 2009-10-21
19:40:42 UTC (rev 15744)
+++ root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCache.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -1,204 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library 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 library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-package org.ajax4jsf.cache;
-
-import java.util.Date;
-import java.util.PriorityQueue;
-
-import org.ajax4jsf.util.LRUMap;
-
-/**
- * @author Nick - mailto:nbelaevski@exadel.com
- * @since 3.1
- */
-public class LRUMapCache implements Cache {
-
- protected static final class CacheMap extends LRUMap<Object, CacheEntry> {
- /**
- *
- */
- private static final long serialVersionUID = -5422668357346537621L;
-
- public CacheMap() {
- super();
- }
-
- public CacheMap(int capacity) {
- super(capacity);
- }
-
- protected PriorityQueue<CacheEntry> expirationQueue = new
PriorityQueue<CacheEntry>();
-
- public CacheEntry put(Object key, CacheEntry value) {
- CacheEntry entry = super.put(key, value);
- if (entry != null) {
- //prolong
- expirationQueue.remove(entry);
- }
-
- if (value.expired != null) {
- expirationQueue.add(value);
- }
-
- return entry;
- }
-
- public CacheEntry remove(Object key) {
- CacheEntry entry = super.remove(key);
- if (entry != null) {
- expirationQueue.remove(entry);
- }
-
- return entry;
- }
-
- public void clear() {
- super.clear();
- expirationQueue.clear();
- }
-
- public void purge() {
- CacheEntry queueEntry = null;
-
- while ((queueEntry = expirationQueue.peek()) != null &&
- queueEntry.isExpired()) {
-
- super.remove(queueEntry.getKey());
- expirationQueue.remove();
- }
- }
- }
-
- protected static final class CacheEntry implements Comparable<CacheEntry> {
-
- private Object key;
-
- private Object value;
-
- private Date expired;
-
- public CacheEntry(Object key, Object value, Date expired) {
- super();
-
- this.key = key;
- this.value = value;
- this.expired = expired;
- }
-
- public Object getKey() {
- return key;
- }
-
- public Object getValue() {
- return value;
- }
-
- public boolean isExpired() {
- if (expired != null) {
- return System.currentTimeMillis() >= expired.getTime();
- } else {
- return false;
- }
- }
-
- //due to PriorityQueue bug in JDK 1.5 comparator should return 0 ONLY if entries are
equal
- public int compareTo(CacheEntry o) {
- //reverse sort order
- int result = expired.compareTo(o.expired);
- if (result == 0) {
- result = key.toString().compareTo(o.key.toString());
- }
-
- return result;
- }
-
- @Override
- public int hashCode() {
- final int prime = 31;
- int result = 1;
- result = prime * result + ((key == null) ? 0 : key.hashCode());
- return result;
- }
-
- //see compareTo()
- @Override
- public boolean equals(Object obj) {
- if (this == obj)
- return true;
- if (obj == null)
- return false;
- if (getClass() != obj.getClass())
- return false;
- CacheEntry other = (CacheEntry) obj;
- if (key == null) {
- if (other.key != null)
- return false;
- } else if (!key.equals(other.key))
- return false;
- return true;
- }
-
- @Override
- public String toString() {
- if (expired == null) {
- return key.toString();
- } else {
- return key + ": " + expired;
- }
- }
- }
-
- private CacheMap map;
-
- public LRUMapCache() {
- this.map = new CacheMap();
- }
-
- public LRUMapCache(int capacity) {
- this.map = new CacheMap(capacity);
- }
-
- public synchronized Object get(Object key) {
- this.map.purge();
-
- CacheEntry entry = this.map.get(key);
- if (entry != null) {
- return entry.getValue();
- }
-
- return null;
- }
-
- public synchronized void put(Object key, Object value, Date expired) {
- this.map.purge();
-
- CacheEntry cacheEntry = new CacheEntry(key, value, expired);
- this.map.put(key, cacheEntry);
- }
-
- public void start() {
- }
-
- public void stop() {
- this.map.clear();
- }
-}
Deleted:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCacheFactory.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCacheFactory.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCacheFactory.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -1,54 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library 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 library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-package org.ajax4jsf.cache;
-
-import java.util.Map;
-
-import org.richfaces.log.RichfacesLogger;
-import org.slf4j.Logger;
-
-
-/**
- * @author Nick - mailto:nbelaevski@exadel.com
- * created 01.05.2007
- *
- */
-public class LRUMapCacheFactory implements CacheFactory {
-
- private static final Logger log = RichfacesLogger.CACHE.getLogger();
-
- public final static String CACHE_SIZE_PARAMETER =
"org.ajax4jsf.cache.LRU_MAP_CACHE_SIZE";
-
- public Cache createCache(Map<?, ?> env) {
- 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");
- return new LRUMapCache();
- } else {
- int parsedSize = Integer.parseInt(size);
- log.info("Creating LRUMap cache instance of " + parsedSize + " items
capacity");
- return new LRUMapCache(parsedSize);
- }
- }
-}
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/OSCacheCacheFactory.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -35,66 +35,53 @@
/**
* @author Nick - mailto:nbelaevski@exadel.com
- * created 01.05.2007
- *
+ * created 01.05.2007
*/
public class OSCacheCacheFactory implements CacheFactory {
- private static final Logger log = RichfacesLogger.CACHE.getLogger();
+ private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
- private Properties loadProperties(URL url) throws IOException {
- Properties properties = new Properties();
+ private static Properties loadProperties() throws IOException {
+ Properties properties = new Properties();
- URL resource = OSCacheCache.class.getResource("oscache.properties");
- if (resource != null) {
- InputStream stream = URLToStreamHelper.urlToStream(resource);
- try {
- properties.load(stream);
- } finally {
- try {
- stream.close();
- } catch (IOException e) {
- // TODO: handle exception
- }
- }
- }
-
- return properties;
+ URL resource = OSCacheCache.class.getResource("oscache.properties");
+ if (resource != null) {
+ InputStream stream = URLToStreamHelper.urlToStream(resource);
+ try {
+ properties.load(stream);
+ } finally {
+ try {
+ stream.close();
+ } catch (IOException e) {
+ // TODO: handle exception
+ }
+ }
+ }
+
+ return properties;
}
-
- private ClassLoader findClassLoader() {
- ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
- if (classLoader == null) {
- classLoader = getClass().getClassLoader();
- }
- if (classLoader == null) {
- classLoader = ClassLoader.getSystemClassLoader();
- }
-
- return classLoader;
- }
-
- public Cache createCache(Map<?, ?> env) {
- Properties cacheProperties = new Properties();
- try {
- cacheProperties.putAll(loadProperties(OSCacheCache.class.getResource("oscache.properties")));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- cacheProperties.putAll(loadProperties(findClassLoader().getResource("oscache.properties")));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- cacheProperties.putAll(env);
-
- log.info("Creating OSCache cache instance using parameters: " +
cacheProperties);
- GeneralCacheAdministrator cacheAdministrator = new
GeneralCacheAdministrator(cacheProperties);
- return new OSCacheCache(cacheAdministrator.getCache());
- }
+ public Cache createCache(Map<?, ?> env) {
+ Properties cacheProperties = new Properties();
+ try {
+ cacheProperties.putAll(loadProperties());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ try {
+ cacheProperties.putAll(loadProperties());
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ cacheProperties.putAll(env);
+
+ LOG.info("Creating OSCache cache instance using parameters: " +
cacheProperties);
+ GeneralCacheAdministrator cacheAdministrator = new
GeneralCacheAdministrator(cacheProperties);
+ return new OSCacheCache(cacheAdministrator.getCache());
+ }
+
}
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMap.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -32,98 +32,82 @@
/**
* @author Nick Belaevski - nbelaevski(a)exadel.com
- * created 02.05.2007
- *
+ * created 02.05.2007
*/
@Deprecated
public class ServletContextInitMap extends AbstractMap<String, String> {
- private ServletContext servletContext;
-
- public ServletContextInitMap(ServletContext servletContext) {
- super();
- this.servletContext = servletContext;
- }
+ private ServletContext servletContext;
- public Set<Map.Entry<String, String>> entrySet() {
- return new AbstractSet<Map.Entry<String, String>>() {
+ public ServletContextInitMap(ServletContext servletContext) {
+ super();
+ this.servletContext = servletContext;
+ }
- public Iterator<Map.Entry<String, String>> iterator() {
- return new Iterator<Map.Entry<String, String>>() {
-
- @SuppressWarnings("unchecked")
- private Enumeration<String> initNames =
servletContext.getInitParameterNames();
-
- public boolean hasNext() {
- return initNames.hasMoreElements();
- }
+ @Override
+ public Set<Map.Entry<String, String>> entrySet() {
+ return new MyAbstractSet();
+ }
- public Map.Entry<String, String> next() {
- String key = (String) initNames.nextElement();
- String value = servletContext.getInitParameter(key);
-
- return new ServletContextInitMapEntry<String,String>(key, value);
- }
+ @Override
+ public String remove(Object key) {
+ throw new UnsupportedOperationException("This map is read-only");
+ }
- public void remove() {
- throw new UnsupportedOperationException("This map is read-only");
- }
-
- };
- }
+ @Override
+ public String put(String key, String value) {
+ throw new UnsupportedOperationException("This map is read-only");
+ }
- @SuppressWarnings("unchecked")
- public int size() {
- int result = 0;
- Enumeration<String> initNames = servletContext.getInitParameterNames();
- while (initNames.hasMoreElements()) {
- initNames.nextElement();
- result++;
- }
+ @Override
+ public void putAll(Map<? extends String, ? extends String> m) {
+ throw new UnsupportedOperationException("This map is read-only");
+ }
- return result;
- }
-
- public boolean isEmpty() {
- return !servletContext.getInitParameterNames().hasMoreElements();
- }
- };
- }
-
- public String remove(Object key) {
- throw new UnsupportedOperationException("This map is read-only");
- }
+ private class MyAbstractSet extends AbstractSet<Map.Entry<String,
String>> {
- public String put(String key, String value) {
- throw new UnsupportedOperationException("This map is read-only");
- }
+ @Override
+ public Iterator<Map.Entry<String, String>> iterator() {
+ return new MyIterator();
+ }
- public void putAll(Map<? extends String, ? extends String> m) {
- throw new UnsupportedOperationException("This map is read-only");
- }
+ @Override
+ public int size() {
+ int result = 0;
-}
+ @SuppressWarnings("unchecked")
+ Enumeration<String> initNames =
servletContext.getInitParameterNames();
+ while (initNames.hasMoreElements()) {
+ initNames.nextElement();
+ result++;
+ }
-class ServletContextInitMapEntry<K, V> implements Map.Entry<K, V> {
+ return result;
+ }
- private K key;
- private V value;
-
- public ServletContextInitMapEntry(K key, V value) {
- super();
- this.key = key;
- this.value = value;
- }
+ @Override
+ public boolean isEmpty() {
+ return !servletContext.getInitParameterNames().hasMoreElements();
+ }
+ }
- public K getKey() {
- return key;
- }
+ private class MyIterator implements Iterator<Map.Entry<String, String>>
{
- public V getValue() {
- return value;
- }
+ @SuppressWarnings("unchecked")
+ private Enumeration<String> initNames =
servletContext.getInitParameterNames();
- public V setValue(V value) {
- throw new UnsupportedOperationException("This map is read-only");
- }
-
-}
\ No newline at end of file
+ public boolean hasNext() {
+ return initNames.hasMoreElements();
+ }
+
+ public Map.Entry<String, String> next() {
+ String key = initNames.nextElement();
+ String value = servletContext.getInitParameter(key);
+
+ return new ServletContextInitMapEntry<String, String>(key, value);
+ }
+
+ public void remove() {
+ throw new UnsupportedOperationException("This map is read-only");
+ }
+ }
+}
Added:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/ServletContextInitMapEntry.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,53 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.ajax4jsf.cache;
+
+import java.util.Map;
+
+/**
+ * User: akolonitsky
+ * Date: Oct 13, 2009
+ */
+class ServletContextInitMapEntry<K, V> implements Map.Entry<K, V> {
+
+ private K key;
+ private V value;
+
+ ServletContextInitMapEntry(K key, V value) {
+ super();
+ this.key = key;
+ this.value = value;
+ }
+
+ public K getKey() {
+ return key;
+ }
+
+ public V getValue() {
+ return value;
+ }
+
+ public V setValue(V value) {
+ throw new UnsupportedOperationException("This map is read-only");
+ }
+
+}
Added: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheEntry.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,105 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+package org.ajax4jsf.cache.lru;
+
+import java.util.Date;
+
+/**
+ * User: akolonitsky
+ * Date: Oct 13, 2009
+ */
+public final class CacheEntry implements Comparable<CacheEntry> {
+
+ private Object key;
+
+ private Object value;
+
+ private Date expired;
+
+ public CacheEntry(Object key, Object value, Date expired) {
+ super();
+
+ this.key = key;
+ this.value = value;
+ this.expired = expired == null ? null : (Date) expired.clone();
+ }
+
+ public Object getKey() {
+ return key;
+ }
+
+ public Object getValue() {
+ return value;
+ }
+
+ public boolean isExpired() {
+ return expired != null && System.currentTimeMillis() >=
expired.getTime();
+ }
+
+ public Date getExpired() {
+ return expired == null ? null : (Date) expired.clone();
+ }
+
+ //due to PriorityQueue bug in JDK 1.5 comparator should return 0 ONLY if entries are
equal
+ public int compareTo(CacheEntry o) {
+ //reverse sort order
+ int result = expired.compareTo(o.expired);
+ if (result == 0) {
+ result = key.toString().compareTo(o.key.toString());
+ }
+
+ return result;
+ }
+
+ @Override
+ public int hashCode() {
+ final int prime = 31;
+ int result = 1;
+ result = prime * result + ((key == null) ? 0 : key.hashCode());
+ return result;
+ }
+
+ //see compareTo()
+ @Override
+ public boolean equals(Object obj) {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass())
+ return false;
+ CacheEntry other = (CacheEntry) obj;
+ if (key == null) {
+ if (other.key != null)
+ return false;
+ } else if (!key.equals(other.key))
+ return false;
+ return true;
+ }
+
+ @Override
+ public String toString() {
+ return expired == null ? key.toString() : key + ": " + expired;
+ }
+}
Added: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/CacheMap.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,93 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+package org.ajax4jsf.cache.lru;
+
+import org.ajax4jsf.util.LRUMap;
+
+import java.util.PriorityQueue;
+
+/**
+ * User: akolonitsky
+ * Date: Oct 13, 2009
+ */
+public final class CacheMap extends LRUMap<Object, CacheEntry> {
+
+ private static final long serialVersionUID = -5422668357346537621L;
+
+ public CacheMap() {
+ super();
+ }
+
+ public CacheMap(int capacity) {
+ super(capacity);
+ }
+
+ private PriorityQueue<CacheEntry> expirationQueue = new
PriorityQueue<CacheEntry>();
+
+ public PriorityQueue<CacheEntry> getExpirationQueue() {
+ return expirationQueue;
+ }
+
+ @Override
+ public CacheEntry put(Object key, CacheEntry value) {
+ CacheEntry entry = super.put(key, value);
+ if (entry != null) {
+ //prolong
+ expirationQueue.remove(entry);
+ }
+
+ if (value.getExpired() != null) {
+ expirationQueue.add(value);
+ }
+
+ return entry;
+ }
+
+ @Override
+ public CacheEntry remove(Object key) {
+ CacheEntry entry = super.remove(key);
+ if (entry != null) {
+ expirationQueue.remove(entry);
+ }
+
+ return entry;
+ }
+
+ @Override
+ public void clear() {
+ super.clear();
+ expirationQueue.clear();
+ }
+
+ public void purge() {
+ CacheEntry queueEntry = expirationQueue.peek();
+
+ while (queueEntry != null && queueEntry.isExpired()) {
+ super.remove(queueEntry.getKey());
+ expirationQueue.remove();
+
+ queueEntry = expirationQueue.peek();
+ }
+ }
+}
+
+
Copied: root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java
(from rev 15712,
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCache.java)
===================================================================
--- root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCache.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,68 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+*/
+
+package org.ajax4jsf.cache.lru;
+
+import java.util.Date;
+
+import org.ajax4jsf.cache.Cache;
+
+/**
+ * @author Nick - mailto:nbelaevski@exadel.com
+ * @since 3.1
+ */
+public class LRUMapCache implements Cache {
+
+ private CacheMap map;
+
+ public LRUMapCache() {
+ this.map = new CacheMap();
+ }
+
+ public LRUMapCache(int capacity) {
+ this.map = new CacheMap(capacity);
+ }
+
+ public synchronized Object get(Object key) {
+ this.map.purge();
+
+ CacheEntry entry = this.map.get(key);
+ if (entry != null) {
+ return entry.getValue();
+ }
+
+ return null;
+ }
+
+ public synchronized void put(Object key, Object value, Date expired) {
+ this.map.purge();
+
+ CacheEntry cacheEntry = new CacheEntry(key, value, expired);
+ this.map.put(key, cacheEntry);
+ }
+
+ public void start() {
+ }
+
+ public void stop() {
+ this.map.clear();
+ }
+}
Copied:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
(from rev 15712,
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/LRUMapCacheFactory.java)
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/cache/lru/LRUMapCacheFactory.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,56 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.ajax4jsf.cache.lru;
+
+import java.util.Map;
+
+import org.richfaces.log.RichfacesLogger;
+import org.slf4j.Logger;
+import org.ajax4jsf.cache.lru.LRUMapCache;
+import org.ajax4jsf.cache.CacheFactory;
+import org.ajax4jsf.cache.Cache;
+
+
+/**
+ * @author Nick - mailto:nbelaevski@exadel.com
+ * created 01.05.2007
+ */
+public class LRUMapCacheFactory implements CacheFactory {
+
+ private static final Logger LOG = RichfacesLogger.CACHE.getLogger();
+
+ public static final String CACHE_SIZE_PARAMETER =
"org.ajax4jsf.cache.LRU_MAP_CACHE_SIZE";
+
+ public Cache createCache(Map<?, ?> env) {
+ 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");
+ return new LRUMapCache();
+ } else {
+ int parsedSize = Integer.parseInt(size);
+ LOG.info("Creating LRUMap cache instance of " + parsedSize + "
items capacity");
+ return new LRUMapCache(parsedSize);
+ }
+ }
+}
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/config/FrameworkConfiguration.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -21,9 +21,9 @@
* framework configuration class
*/
-public class FrameworkConfiguration {
+public final class FrameworkConfiguration {
- private static final Logger logger = RichfacesLogger.CONFIG.getLogger();
+ private static final Logger LOGGER = RichfacesLogger.CONFIG.getLogger();
private Map<InitParam, String> initParams = new EnumMap<InitParam,
String>(InitParam.class);
@@ -32,7 +32,7 @@
private static final Pattern ALLOWABLE_NUMBER = Pattern.compile("^\\d+$");
- private FrameworkConfiguration(ExternalContext externalContext) {
+ private FrameworkConfiguration(ExternalContext externalContext) {
processInitParams(externalContext);
}
@@ -46,11 +46,11 @@
return new FrameworkConfiguration(externalContext);
}
- private boolean isBooleanValue(InitParam param, String value) {
+ private boolean isBooleanValue(String value) {
return ALLOWABLE_BOOLEANS.matcher(value).matches();
}
- private boolean isNumberValue(InitParam param, String value) {
+ private boolean isNumberValue(String value) {
return ALLOWABLE_NUMBER.matcher(value).matches();
}
@@ -62,10 +62,10 @@
return ((Integer)resolveELParam(FacesContext.getCurrentInstance(), value,
java.lang.Integer.class)).intValue();
}
- if(isNumberValue(param, value)) {
+ if(isNumberValue(value)) {
return Integer.parseInt(value);
}
- logger.error("option value: " + param.getQualifiedName() + " is not
an integer number set default value: " + param.getDefaultValue());
+ LOGGER.error("option value: " + param.getQualifiedName() + " is not
an integer number set default value: " + param.getDefaultValue());
return Integer.parseInt(param.getDefaultValue());
}
@@ -76,11 +76,11 @@
return ((Boolean)resolveELParam(FacesContext.getCurrentInstance(), value,
java.lang.Boolean.class)).booleanValue();
}
- if(isBooleanValue(param, value)) {
+ if(isBooleanValue(value)) {
return Boolean.parseBoolean(value);
}
- logger.error("option value: " + param.getQualifiedName() + " is not a
boolean value set default value: " + param.getDefaultValue());
+ LOGGER.error("option value: " + param.getQualifiedName() + " is not a
boolean value set default value: " + param.getDefaultValue());
return Boolean.parseBoolean(param.getDefaultValue());
}
@@ -110,7 +110,7 @@
}
}
- public Object resolveELParam(FacesContext context, String value, Class <?>
expectedClass) {
+ public Object resolveELParam(FacesContext context, String value, Class <?>
expectedClass) {
ExpressionFactory factory = context.getApplication().getExpressionFactory();
ValueExpression valueExpression = factory.createValueExpression(context.getELContext(),
value, expectedClass);
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/event/CacheInitializationListener.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -18,21 +18,13 @@
public void init(SystemEvent event) {
//TODO read configuration ??
}
-
-
- @Override
- public void destroy(SystemEvent event) {
- CacheManager cacheManager = CacheManager.getInstance();
- Map <String, Cache> caches = cacheManager.getCaches();
- if(!caches.isEmpty()) {
- Set <String> cacheNames = caches.keySet();
- for(String cacheName: cacheNames) {
- try {
- cacheManager.destroyCache(cacheName);
- } catch (Exception e) {
- looger.error("Error during stop cache " + cacheName, e);
- }
- }
- }
- }
+
+ @Override
+ public void destroy(SystemEvent event) {
+ try {
+ CacheManager.getInstance().destroy();
+ } catch (Exception e) {
+ looger.error("Error during stop caches.", e);
+ }
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/AjaxRendererUtils.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -60,7 +60,7 @@
*
* Some utilites for render AJAX components.
*/
-public class AjaxRendererUtils {
+public final class AjaxRendererUtils {
/**
* Name Javasript function for submit AJAX request
@@ -97,7 +97,7 @@
*/
public static final String LIMITRENDER_ATTR_NAME = "limitRender";
- private static final Logger log = RichfacesLogger.RENDERKIT.getLogger();
+ private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
public static final String AJAX_REGIONS_ATTRIBUTE = "reRender";
@@ -124,7 +124,7 @@
public static final String SIMILARITY_GROUPING_ID_ATTR =
"similarityGroupingId";
- private static final RendererUtils rendererUtils = RendererUtils.getInstance();
+ private static final RendererUtils RENDERER_UTILS = RendererUtils.getInstance();
public static final String ALL = "@all";
@@ -137,8 +137,8 @@
public static final String NONE = "@none";
public static final Collection<String> NONE_SET = Collections.singleton(NONE);
-
- /**
+
+ /**
* Static class - protect constructor
*
*/
@@ -237,7 +237,7 @@
// onEvent.append("; return false;");
// }
// }
-// log.debug(Messages.getMessage(Messages.BUILD_ONCLICK_INFO, uiComponent
+// LOG.debug(Messages.getMessage(Messages.BUILD_ONCLICK_INFO, uiComponent
// .getId(), onEvent.toString()));
return onEvent;
@@ -313,15 +313,15 @@
public static AjaxEventOptions buildEventOptions(FacesContext facesContext, UIComponent
component, AjaxClientBehavior ajaxBehavior) {
AjaxEventOptions ajaxEventOptions = new AjaxEventOptions();
- Map<String, Object> parametersMap =
rendererUtils.createParametersMap(facesContext, component);
+ Map<String, Object> parametersMap =
RENDERER_UTILS.createParametersMap(facesContext, component);
String ajaxStatusName = getAjaxStatus(component);
if(ajaxBehavior != null) {
ajaxStatusName = ajaxBehavior.getStatus() != null ? ajaxBehavior.getStatus() :
ajaxStatusName;
- appenAjaxBehaviorOptions(facesContext, ajaxBehavior, ajaxEventOptions);
+ appenAjaxBehaviorOptions(ajaxBehavior, ajaxEventOptions);
} else {
- appendComponentOptions(facesContext, component, ajaxEventOptions, parametersMap);
+ appendComponentOptions(facesContext, component, ajaxEventOptions);
}
if (ajaxStatusName != null && ajaxStatusName.length() != 0) {
@@ -335,15 +335,11 @@
return ajaxEventOptions;
}
- /**
- * @param eventHandlerValue
- * @return
- */
private static boolean isNotEmpty(String value) {
return value != null && value.length() != 0;
}
- private static void appenAjaxBehaviorOptions(FacesContext context, AjaxClientBehavior
behavior, AjaxEventOptions ajaxEventOptions) {
+ private static void appenAjaxBehaviorOptions(AjaxClientBehavior behavior,
AjaxEventOptions ajaxEventOptions) {
for(BehaviorEventOptionsData optionsData : BehaviorEventOptionsData.values()) {
String eventHandlerValue = optionsData.getAttributeValue(behavior);
if (isNotEmpty(eventHandlerValue)) {
@@ -352,8 +348,8 @@
}
}
- private static void appendComponentOptions(FacesContext facesContext, UIComponent
component,
- AjaxEventOptions ajaxEventOptions, Map<String, Object> parametersMap) {
+ private static void appendComponentOptions(FacesContext facesContext, UIComponent
component,
+ AjaxEventOptions ajaxEventOptions) {
for (EventOptionsData eventOptionsData : EventOptionsData.values()) {
String behaviorName = eventOptionsData.toString();
@@ -426,8 +422,8 @@
// String ajaxActionURL = ajaxContext.getAjaxActionURL(facesContext);
// if (omitDefaultActionUrl) {
// UIComponent form = getNestingForm(uiComponent);
-// if (form != null && !rendererUtils.isBooleanAttribute(form,
"ajaxSubmit")) {
-// if (rendererUtils.getActionUrl(facesContext).equals(ajaxActionURL)) {
+// if (form != null && !RENDERER_UTILS.isBooleanAttribute(form,
"ajaxSubmit")) {
+// if (RENDERER_UTILS.getActionUrl(facesContext).equals(ajaxActionURL)) {
// ajaxActionURL = null;
// }
// }
@@ -704,7 +700,7 @@
// Tokenize string.
else if (valueToSet instanceof String) {
String areasString = ((String) valueToSet).trim();
- if (areasString.indexOf(",") > 0 || areasString.indexOf(" ")
> 0) {
+ if (areasString.contains(",") || areasString.contains(" ")) {
return new LinkedHashSet<String>(Arrays.asList(areasString.split(
"(\\s*,\\s*)|(\\s+)")));
} else {
@@ -743,7 +739,7 @@
// statusId = status
// .getClientId(FacesContext.getCurrentInstance());
// } else {
-// log.warn(Messages.getMessage(
+// LOG.warn(Messages.getMessage(
// Messages.AJAX_STATUS_COMPONENT_NOT_FOWND_WARNING,
// component.getId()));
// }
@@ -835,9 +831,10 @@
* @return
*/
public static String getAbsoluteId(UIComponent component) {
- if (component == null)
+ if (component == null) {
throw new NullPointerException(Messages
.getMessage(Messages.COMPONENT_NULL_ERROR_2));
+ }
StringBuffer idBuf = new StringBuffer();
@@ -852,7 +849,7 @@
}
}
idBuf.insert(0, NamingContainer.SEPARATOR_CHAR);
- log.debug(Messages.getMessage(Messages.CALCULATE_COMPONENT_ID_INFO,
+ LOG.debug(Messages.getMessage(Messages.CALCULATE_COMPONENT_ID_INFO,
component.getId(), idBuf.toString()));
return idBuf.toString();
}
@@ -917,7 +914,7 @@
ExternalContext externalContext = context.getExternalContext();
Map<String, Object> requestMap = externalContext.getRequestMap();
Set<String> rendered = ajaxContext.getAjaxRenderedAreas();
- StringBuffer senderString = new StringBuffer();
+
// write special area for list of rendered elements. Client-side
// Java
// Script
@@ -929,23 +926,18 @@
// information,
// but I want to keep simple html ( xhtml ) document - on case
// I have troubles with microsoft XMLHTTP validations.
- out
- .startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG,
- component);
- out.writeAttribute(HTML.NAME_ATTRIBUTE,
- AjaxContainerRenderer.AJAX_UPDATE_HEADER, null);
+ out.startElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG, component);
+ out.writeAttribute(HTML.NAME_ATTRIBUTE, AjaxContainerRenderer.AJAX_UPDATE_HEADER,
null);
+
+ StringBuffer senderString = new StringBuffer();
for (Iterator<String> it = rendered.iterator(); it.hasNext();) {
- String id = (String) it.next();
- // out.startElement(AJAX_RESULT_TAG, component);
- // out.writeText(id,null);
- // out.endElement(AJAX_RESULT_TAG);
+ String id = it.next();
senderString.append(id);
if (it.hasNext()) {
senderString.append(',');
}
}
- out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR,
- senderString, null);
+ out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, senderString, null);
out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
// For sequences and client-saved states.
@@ -962,8 +954,7 @@
AjaxContainerRenderer.AJAX_FLAG_HEADER, null);
out.writeAttribute(HTML.NAME_ATTRIBUTE,
AjaxContainerRenderer.AJAX_FLAG_HEADER, null);
- out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR,
- "true", null);
+ out.writeAttribute(AjaxContainerRenderer.AJAX_RESULT_GROUP_ATTR, "true",
null);
out.endElement(AjaxContainerRenderer.AJAX_RESULT_GROUP_TAG);
// set response header with list of rendered ID's
Object response = externalContext.getResponse();
@@ -974,24 +965,18 @@
HttpServletResponse httpResponse = (HttpServletResponse) response;
// httpResponse.setHeader(AjaxContainerRenderer.AJAX_UPDATE_HEADER,
// senderString.toString());
- httpResponse.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER,
- "true");
+ httpResponse.setHeader(AjaxContainerRenderer.AJAX_FLAG_HEADER, "true");
} else {
try {
Method setHeadergMethod = response.getClass()
- .getMethod("setHeader",
- new Class[] { String.class, String.class });
+ .getMethod("setHeader", new Class[] { String.class, String.class });
// setHeadergMethod.invoke(response, new Object[] {
// AjaxContainerRenderer.AJAX_UPDATE_HEADER,
// senderString.toString() });
- setHeadergMethod.invoke(response, new Object[] {
- AjaxContainerRenderer.AJAX_FLAG_HEADER, "true" });
+ setHeadergMethod.invoke(response, AjaxContainerRenderer.AJAX_FLAG_HEADER,
"true");
} catch (Exception e) {
- log
- .error(Messages
- .getMessage(Messages.DETECTING_ENCODING_DISABLED_ERROR));
- log.error(Messages.getMessage(
- Messages.OBTAIN_RESPONSE_SET_HEADER_ERROR, e));
+ LOG.error(Messages.getMessage(Messages.DETECTING_ENCODING_DISABLED_ERROR));
+ LOG.error(Messages.getMessage(Messages.OBTAIN_RESPONSE_SET_HEADER_ERROR, e));
}
}
Map<String, Object> responseDataMap = ajaxContext.getResponseDataMap();
@@ -999,13 +984,10 @@
AJAXDataSerializer serializer = (AJAXDataSerializer) ServicesUtils
.getServiceInstance(AJAXDataSerializer.SERVICE);
// Put data to JavaScript handlers, inside <span> elements.
- for (Iterator<String> dataIterator = responseDataMap.keySet().iterator();
dataIterator
- .hasNext();) {
- Object dataKey = dataIterator.next();
+ for (Map.Entry<String, Object> entry : responseDataMap.entrySet()) {
out.startElement(HTML.SPAN_ELEM, component);
- out.writeAttribute(HTML.id_ATTRIBUTE, dataKey, null);
- String dataString = serializer.asString(responseDataMap
- .get(dataKey));
+ out.writeAttribute(HTML.id_ATTRIBUTE, entry.getKey(), null);
+ String dataString = serializer.asString(entry.getValue());
out.write(dataString);
out.endElement(HTML.SPAN_ELEM);
}
@@ -1015,11 +997,10 @@
out.startElement(HTML.SPAN_ELEM, component);
out.writeAttribute(HTML.id_ATTRIBUTE, ONCOMPLETE_CONTENT_ID, null);
out.writeText(oncomplete,null);
- out.endElement(HTML.SPAN_ELEM);
+ out.endElement(HTML.SPAN_ELEM);
}
// For self-rendered case, we use own methods for replace stateKey by
- // real value
- // in XML filter.
+ // real value in XML filter.
// if(ajaxContext.isSelfRender()){
// saveViewState(context, out);
// }
@@ -1095,14 +1076,11 @@
*/
private static void loadBundles(FacesContext context, UIComponent component) {
// Iterate over cildrens
- for (Iterator<UIComponent> iter = component.getChildren().iterator();
iter.hasNext();) {
- UIComponent child = (UIComponent) iter.next();
+ for (UIComponent child : component.getChildren()) {
loadCildBundles(context, child);
}
// Iterate over facets
- for (Iterator<UIComponent> iter = component.getFacets().values().iterator();
iter
- .hasNext();) {
- UIComponent child = (UIComponent) iter.next();
+ for (UIComponent child : component.getFacets().values()) {
loadCildBundles(context, child);
}
}
@@ -1146,7 +1124,6 @@
/**
* @param facesContext
* @param component
- * @param id
*/
public static void addRegionsFromComponent(UIComponent component, FacesContext
facesContext) {
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/HandlersChain.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -46,7 +46,7 @@
*/
public final class HandlersChain {
- private static final Logger log = RichfacesLogger.RENDERKIT.getLogger();
+// private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
private boolean hasSubmittingBehavior = false;
@@ -58,8 +58,8 @@
//TODO: review for optimization
private List<String> handlers = new ArrayList<String>(2);
-
- private final boolean isNotEmpty(String s) {
+
+ private static boolean isNotEmpty(String s) {
return s != null && s.length() != 0;
}
@@ -83,7 +83,7 @@
this.includeClientId = includeClientId;
}
- private final List<ClientBehavior> getBehaviorsList(String behaviorName) {
+ private List<ClientBehavior> getBehaviorsList(String behaviorName) {
List<ClientBehavior> behaviors = null;
if (component instanceof ClientBehaviorHolder) {
ClientBehaviorHolder clientBehaviorHolder = (ClientBehaviorHolder) component;
@@ -122,7 +122,7 @@
}
public void addBehaviors(FacesContext context, String evantName) {
- addBehaviors(context, evantName, null);
+ addBehaviors(context, evantName, null);
}
public void addBehaviors(FacesContext context, String evantName, String
defaultEventName) {
String name = evantName;
@@ -131,23 +131,25 @@
behaviorsList = getBehaviorsList(defaultEventName);
name = defaultEventName;
}
- if (behaviorsList != null) {
- ClientBehaviorContext behaviorContext =
ClientBehaviorContext.createClientBehaviorContext(
- context, component, name, includeClientId ? component.getClientId(context) : null,
- getParameters(context));
-
- for (ClientBehavior clientBehavior : behaviorsList) {
- String behaviorScript = clientBehavior.getScript(behaviorContext);
- if (isNotEmpty(behaviorScript)) {
- if (clientBehavior.getHints().contains(ClientBehaviorHint.SUBMITTING)) {
- hasSubmittingBehavior = true;
- }
-
- handlers.add(behaviorScript);
- }
- }
- }
- }
+ if (behaviorsList == null) {
+ return;
+ }
+
+ ClientBehaviorContext behaviorContext =
ClientBehaviorContext.createClientBehaviorContext(
+ context, component, name, includeClientId ? component.getClientId(context) :
null,
+ getParameters(context));
+
+ for (ClientBehavior clientBehavior : behaviorsList) {
+ String behaviorScript = clientBehavior.getScript(behaviorContext);
+ if (isNotEmpty(behaviorScript)) {
+ if (clientBehavior.getHints().contains(ClientBehaviorHint.SUBMITTING)) {
+ hasSubmittingBehavior = true;
+ }
+
+ handlers.add(behaviorScript);
+ }
+ }
+ }
public String toScript() {
String result = null;
Modified:
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/ajax4jsf/renderkit/RendererBase.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -54,55 +54,63 @@
* logger for common cases.
*/
protected static final String JAVASCRIPT_NAMESPACE = "Exadel";
- private static final Logger log = RichfacesLogger.RENDERKIT.getLogger();
- private static final RendererUtils utils = RendererUtils.getInstance();
+ private static final Logger LOG = RichfacesLogger.RENDERKIT.getLogger();
+ private static final RendererUtils UTILS = RendererUtils.getInstance();
private SkinFactory skinFactory = null;
- /* (non-Javadoc)
- * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext,
javax.faces.component.UIComponent)
- */
- public void decode(FacesContext context, UIComponent component) {
- // Test for correct parameters.
- if (context == null) throw new
NullPointerException(Messages.getMessage(Messages.CONTEXT_NULL_ERROR,
"decode"));
- if (component == null) throw new
NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR,
"decode"));
- if (! getComponentClass().isInstance(component)) throw new
IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR, "",
getComponentClass().getName()));
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.START_DECODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
- }
- preDecode(context,component);
+ /* (non-Javadoc)
+ * @see javax.faces.render.Renderer#decode(javax.faces.context.FacesContext,
javax.faces.component.UIComponent)
+ */
+ @Override
+ public void decode(FacesContext context, UIComponent component) {
+ // Test for correct parameters.
+ checkNull(context, component, "decode");
+
+ if (!getComponentClass().isInstance(component)) {
+ throw new
IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR,
"",
+ getComponentClass().getName()));
+ }
+
+ if (LOG.isDebugEnabled()) {
+ LOG.debug(Messages.getMessage(Messages.START_DECODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
+ }
+ preDecode(context, component);
+
// TODO - create set od common decoders ( UIInput, ActionSource etc. ) for
process decoding.
if (component.isRendered()) {
- decodeBehaviors(context, component);
- doDecode(context, component);
- }
- }
+ decodeBehaviors(context, component);
+ doDecode(context, component);
+ }
+ }
- protected void decodeBehaviors(FacesContext context, UIComponent component) {
- if (component instanceof ClientBehaviorHolder) {
- ClientBehaviorHolder holder = (ClientBehaviorHolder) component;
- Map<String, List<ClientBehavior>> behaviors =
holder.getClientBehaviors();
- if (!behaviors.isEmpty()) {
- ExternalContext external = context.getExternalContext();
- Map<String, String> params = external.getRequestParameterMap();
- String behaviorEvent =
params.get("javax.faces.behavior.event");
+ protected void decodeBehaviors(FacesContext context, UIComponent component) {
+ if (!(component instanceof ClientBehaviorHolder)) {
+ return;
+ }
- if (null != behaviorEvent) {
- List<ClientBehavior> behaviorsForEvent =
behaviors.get(behaviorEvent);
+ ClientBehaviorHolder holder = (ClientBehaviorHolder) component;
+ Map<String, List<ClientBehavior>> behaviors =
holder.getClientBehaviors();
+ if (behaviors.isEmpty()) {
+ return;
+ }
- if (behaviors != null && behaviors.size() > 0) {
- String behaviorSource =
params.get("javax.faces.source");
- String clientId = component.getClientId();
- if (null != behaviorSource &&
behaviorSource.equals(clientId)) {
- for (ClientBehavior behavior: behaviorsForEvent) {
- behavior.decode(context, component);
- }
- }
- }
- }
+ ExternalContext external = context.getExternalContext();
+ Map<String, String> params = external.getRequestParameterMap();
+ String behaviorEvent = params.get("javax.faces.behavior.event");
+ if (behaviorEvent == null) {
+ return;
+ }
+
+ List<ClientBehavior> behaviorsForEvent = behaviors.get(behaviorEvent);
+ String behaviorSource = params.get("javax.faces.source");
+ String clientId = component.getClientId();
+ if (null != behaviorSource && behaviorSource.equals(clientId)) {
+ for (ClientBehavior behavior: behaviorsForEvent) {
+ behavior.decode(context, component);
}
}
- }
+ }
protected void preDecode(FacesContext context, UIComponent component) {
}
@@ -114,13 +122,13 @@
/* (non-Javadoc)
* @see javax.faces.render.Renderer#encodeBegin(javax.faces.context.FacesContext,
javax.faces.component.UIComponent)
*/
- public void encodeBegin(FacesContext context, UIComponent component) throws IOException
{
+ @Override
+ public void encodeBegin(FacesContext context, UIComponent component) throws
IOException {
// Test for correct parameters.
- if (context == null) throw new
NullPointerException(Messages.getMessage(Messages.CONTEXT_NULL_ERROR,
"encodeBegin"));
- if (component == null) throw new
NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR,
"encodeBegin"));
- if (! getComponentClass().isInstance(component)) throw new
IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR,
component.getClientId(context), getComponentClass().getName()));
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.START_ENCODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
+ checkForCorrectParams(context, component, "encodeBegin");
+
+ if(LOG.isDebugEnabled()){
+ LOG.debug(Messages.getMessage(Messages.START_ENCODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
}
preEncodeBegin(context,component);
if (component.isRendered()) {
@@ -128,19 +136,36 @@
doEncodeBegin(writer, context, component);
}
}
-
-
- /* (non-Javadoc)
- * @see javax.faces.render.Renderer#encodeChildren(javax.faces.context.FacesContext,
javax.faces.component.UIComponent)
- */
- public void encodeChildren(FacesContext context, UIComponent component) throws
IOException {
+ private void checkForCorrectParams(FacesContext context, UIComponent component,
String exceptionMessageParam) {
+ checkNull(context, component, exceptionMessageParam);
+
+ if (!getComponentClass().isInstance(component)) {
+ throw new
IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR,
component.getClientId(context), getComponentClass().getName()));
+ }
+ }
+
+ private void checkNull(Object context, Object component, String
exceptionMessageParam) {
+ if (context == null) {
+ throw new
NullPointerException(Messages.getMessage(Messages.CONTEXT_NULL_ERROR,
exceptionMessageParam));
+ }
+
+ if (component == null) {
+ throw new
NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR,
exceptionMessageParam));
+ }
+ }
+
+
+ /* (non-Javadoc)
+ * @see javax.faces.render.Renderer#encodeChildren(javax.faces.context.FacesContext,
javax.faces.component.UIComponent)
+ */
+ @Override
+ public void encodeChildren(FacesContext context, UIComponent component) throws
IOException {
// Test for correct parameters.
- if (context == null) throw new
NullPointerException(Messages.getMessage(Messages.CONTEXT_NULL_ERROR,
"encodeBegin"));
- if (component == null) throw new
NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR,
"encodeBegin"));
- if (! getComponentClass().isInstance(component)) throw new
IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR,
component.getClientId(context), getComponentClass().getName()));
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.CHILDREN_ENCODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
+ checkForCorrectParams(context, component, "encodeBegin");
+
+ if(LOG.isDebugEnabled()){
+ LOG.debug(Messages.getMessage(Messages.CHILDREN_ENCODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
}
preEncodeBegin(context,component);
if (component.isRendered()) {
@@ -152,17 +177,17 @@
/* (non-Javadoc)
* @see javax.faces.render.Renderer#encodeEnd(javax.faces.context.FacesContext,
javax.faces.component.UIComponent)
*/
- public void encodeEnd(FacesContext context, UIComponent component) throws IOException {
+ @Override
+ public void encodeEnd(FacesContext context, UIComponent component) throws IOException
{
// Test for correct parameters.
- if (context == null) throw new
NullPointerException(Messages.getMessage(Messages.CONTEXT_NULL_ERROR,
"encodeEnd"));
- if (component == null) throw new
NullPointerException(Messages.getMessage(Messages.COMPONENT_NULL_ERROR,
"encodeEnd"));
- if (! getComponentClass().isInstance(component)) throw new
IllegalArgumentException(Messages.getMessage(Messages.COMPONENT_CLASS_ERROR,
component.getClientId(context), getComponentClass().getName()));
+ checkForCorrectParams(context, component, "encodeEnd");
+
if (component.isRendered()) {
ResponseWriter writer = context.getResponseWriter();
doEncodeEnd(writer, context, component);
}
- if(log.isDebugEnabled()){
- log.debug(Messages.getMessage(Messages.FINISH_ENCODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
+ if(LOG.isDebugEnabled()){
+ LOG.debug(Messages.getMessage(Messages.FINISH_ENCODING_COMPONENT_INFO,
component.getClientId(context), component.getClass().getName()));
}
}
@@ -174,7 +199,7 @@
* @param context - current {@link FacesContext }
* @return
*/
- protected Skin getSkin(FacesContext context) {
+ protected Skin getSkin(FacesContext context) {
if (skinFactory == null) {
skinFactory = SkinFactory.getInstance();
@@ -194,7 +219,7 @@
* @return Returns the utils.
*/
public RendererUtils getUtils() {
- return utils;
+ return UTILS;
}
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/VersionBean.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/VersionBean.java 2009-10-21
19:40:42 UTC (rev 15744)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/VersionBean.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -61,7 +61,7 @@
*/
public static class Version {
- public static final String _versionInfo =
"v."+MAJOR_VERSION+"."+MINOR_VERSION+"."+REVISION+SCM_REVISION;
+ public static final String _versionInfo = "v."+MAJOR_VERSION+ '.'
+MINOR_VERSION+ '.' +REVISION+SCM_REVISION;
public static final String _resourceVersionInfo = MAJOR_VERSION + "_" +
MINOR_VERSION + "_" + REVISION;
Added:
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/ComponentCallback.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,152 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.richfaces.context;
+
+import org.ajax4jsf.component.AjaxClientBehavior;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+import org.ajax4jsf.renderkit.RendererUtils;
+
+import javax.faces.component.visit.VisitCallback;
+import javax.faces.component.visit.VisitResult;
+import javax.faces.component.visit.VisitContext;
+import javax.faces.component.UIComponent;
+import javax.faces.component.behavior.ClientBehaviorHolder;
+import javax.faces.component.behavior.ClientBehavior;
+import javax.faces.context.FacesContext;
+import java.util.Collection;
+import java.util.LinkedHashSet;
+import java.util.List;
+
+/**
+ * User: akolonitsky
+ * Date: Oct 13, 2009
+ */
+abstract class ComponentCallback implements VisitCallback {
+
+ private final String behaviorEvent;
+
+ private boolean handleAll;
+
+ private boolean handleNone;
+
+ private Collection<String> componentIds = new LinkedHashSet<String>();
+
+ ComponentCallback(String behaviorEvent, boolean handleNone,
+ boolean handleAll) {
+ super();
+ this.behaviorEvent = behaviorEvent;
+ this.handleNone = handleNone;
+ this.handleAll = handleAll;
+ }
+
+ protected void addDefaultComponents(Collection<String> ids) {
+
+ }
+
+ private AjaxClientBehavior findBehavior(UIComponent target) {
+ if (behaviorEvent == null || !(target instanceof ClientBehaviorHolder)) {
+ return null;
+ }
+
+ ClientBehaviorHolder behaviorHolder = (ClientBehaviorHolder) target;
+ List<ClientBehavior> behaviors =
behaviorHolder.getClientBehaviors().get(behaviorEvent);
+ if (behaviors == null) {
+ return null;
+ }
+
+ for (ClientBehavior behavior : behaviors) {
+ if (behavior instanceof AjaxClientBehavior && !((AjaxClientBehavior)
behavior).isDisabled()) {
+ //TODO need more reliable algorithm
+ return (AjaxClientBehavior) behavior;
+ }
+ }
+
+ return null;
+ }
+
+ protected abstract Object getBehaviorAttributeValue(AjaxClientBehavior behavior);
+
+ protected abstract Object getAttributeValue(UIComponent component);
+
+ protected void doVisit(FacesContext context, UIComponent target, AjaxClientBehavior
behavior) {
+ Object attributeObject;
+ if (behavior == null) {
+ attributeObject = getAttributeValue(target);
+ } else {
+ attributeObject = getBehaviorAttributeValue(behavior);
+ }
+
+ Collection<String> attributeIds =
AjaxRendererUtils.asSet(attributeObject);
+ if (attributeIds == null || attributeIds.isEmpty()) {
+ return;
+ }
+
+ if (attributeIds.contains(AjaxRendererUtils.ALL)) {
+ if (!AjaxRendererUtils.ALL_SET.equals(attributeIds)) {
+ //TODO: log
+ }
+
+ handleAll = true;
+ } else {
+ handleAll = false;
+
+ if (attributeIds.contains(AjaxRendererUtils.NONE)) {
+ if (!AjaxRendererUtils.NONE_SET.equals(attributeIds)) {
+ //TODO: log
+ }
+
+ handleNone = true;
+ } else {
+ //asSet() returns copy of original set and we're free to modify it
+ addDefaultComponents(attributeIds);
+
+ componentIds.addAll(RendererUtils.getInstance().findComponentsFor(
+ context, target, attributeIds));
+ }
+ }
+ }
+
+ public final VisitResult visit(VisitContext visitContext, UIComponent target) {
+ AjaxClientBehavior ajaxBehavior = null;
+ if (behaviorEvent != null) {
+ ajaxBehavior = findBehavior(target);
+ }
+
+ doVisit(visitContext.getFacesContext(), target, ajaxBehavior);
+
+ return VisitResult.COMPLETE;
+ }
+
+ public Collection<String> getComponentIds() {
+ return componentIds;
+ }
+
+ public boolean isHandleAll() {
+ return handleAll;
+ }
+
+ public boolean isHandleNone() {
+ return handleNone;
+ }
+}
+
+
Added: root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/ContextProvider.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,62 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.richfaces.context;
+
+import javax.faces.context.FacesContext;
+import java.util.Map;
+
+/**
+ * @author akolonitsky
+ * @since Oct 13, 2009
+ */
+public abstract class ContextProvider {
+
+ protected final String singletonContextAttributeName;
+
+ protected ContextProvider(String attributeSuffixName) {
+ this.singletonContextAttributeName = SingletonsContext.class.getName() +
':' + attributeSuffixName;
+ }
+
+ protected static AttributesContext createContext() {
+ return new AttributesContext();
+ }
+
+ protected abstract Map<? super String, Object> getContextMap(FacesContext
facesContext);
+
+ protected AttributesContext createAndStoreContext(FacesContext context) {
+ AttributesContext instance = createContext();
+ getContextMap(context).put(singletonContextAttributeName, instance);
+
+ return instance;
+ }
+
+ public AttributesContext get(FacesContext context) {
+ Map<? super String, Object> contextMap = getContextMap(context);
+
+ AttributesContext instance = (AttributesContext)
contextMap.get(singletonContextAttributeName);
+ if (instance == null) {
+ instance = createAndStoreContext(context);
+ }
+
+ return instance;
+ }
+}
Added:
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/ExecuteComponentCallback.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,57 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.richfaces.context;
+
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+import org.ajax4jsf.component.AjaxClientBehavior;
+
+import javax.faces.component.UIComponent;
+import java.util.Collection;
+
+/**
+ * @author akolonitsky
+ * @since Oct 13, 2009
+ */
+class ExecuteComponentCallback extends ComponentCallback {
+
+ ExecuteComponentCallback(String behaviorEvent) {
+ super(behaviorEvent, false, true);
+ }
+
+ @Override
+ protected void addDefaultComponents(Collection<String> ids) {
+ super.addDefaultComponents(ids);
+ ids.add(AjaxRendererUtils.THIS);
+ }
+
+ @Override
+ public Object getAttributeValue(UIComponent component) {
+ return component.getAttributes().get("execute");
+ }
+
+ @Override
+ protected Object getBehaviorAttributeValue(AjaxClientBehavior behavior) {
+ return behavior.getExecute();
+ }
+}
+
+
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/PartialViewContextImpl.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -82,179 +82,8 @@
);
}
- private abstract static class ComponentCallback implements VisitCallback {
-
- private final String behaviorEvent;
-
- private boolean handleAll;
-
- private boolean handleNone;
-
- private Collection<String> componentIds = new LinkedHashSet<String>();
-
- public ComponentCallback(String behaviorEvent, boolean handleNone,
- boolean handleAll) {
- super();
- this.behaviorEvent = behaviorEvent;
- this.handleNone = handleNone;
- this.handleAll = handleAll;
- }
-
- protected void addDefaultComponents(Collection<String> ids) {
-
- }
-
- private AjaxClientBehavior findBehavior(UIComponent target) {
- AjaxClientBehavior result = null;
- if (behaviorEvent != null) {
- if (target instanceof ClientBehaviorHolder) {
- ClientBehaviorHolder behaviorHolder = (ClientBehaviorHolder) target;
- List<ClientBehavior> behaviors =
behaviorHolder.getClientBehaviors().get(behaviorEvent);
- if (behaviors != null) {
- for (ClientBehavior behavior : behaviors) {
- if (behavior instanceof AjaxClientBehavior) {
- AjaxClientBehavior ajaxBehavior = (AjaxClientBehavior) behavior;
- if (!ajaxBehavior.isDisabled()) {
- //TODO need more reliable algorithm
- result = (AjaxClientBehavior) behavior;
- break;
- }
- }
- }
- }
- }
- }
-
- if (result == null) {
- //TODO: log
- }
-
- return result;
- }
-
- protected abstract Object getBehaviorAttributeValue(AjaxClientBehavior behavior);
-
- protected abstract Object getAttributeValue(UIComponent component);
-
- protected void doVisit(FacesContext context, UIComponent target, AjaxClientBehavior
behavior) {
- Object attributeObject = null;
- if (behavior != null) {
- attributeObject = getBehaviorAttributeValue(behavior);
- } else {
- attributeObject = getAttributeValue(target);
- }
-
- Collection<String> attributeIds = AjaxRendererUtils.asSet(attributeObject);
- if (attributeIds != null && !attributeIds.isEmpty()) {
- if (attributeIds.contains(AjaxRendererUtils.ALL)) {
- if (!AjaxRendererUtils.ALL_SET.equals(attributeIds)) {
- //TODO: log
- }
-
- handleAll = true;
- } else {
- handleAll = false;
-
- if (attributeIds.contains(AjaxRendererUtils.NONE)) {
- if (!AjaxRendererUtils.NONE_SET.equals(attributeIds)) {
- //TODO: log
- }
-
- handleNone = true;
- } else {
- //asSet() returns copy of original set and we're free to modify it
- addDefaultComponents(attributeIds);
-
- componentIds.addAll(RendererUtils.getInstance().findComponentsFor(
- context, target, attributeIds));
- }
- }
- }
- }
-
- public final VisitResult visit(VisitContext visitContext, UIComponent target) {
- AjaxClientBehavior ajaxBehavior = null;
- if (behaviorEvent != null) {
- ajaxBehavior = findBehavior(target);
- }
-
- doVisit(visitContext.getFacesContext(), target, ajaxBehavior);
-
- return VisitResult.COMPLETE;
- }
-
- public Collection<String> getComponentIds() {
- return componentIds;
- }
-
- public boolean isHandleAll() {
- return handleAll;
- }
-
- public boolean isHandleNone() {
- return handleNone;
- }
- }
-
- private static class ExecuteComponentCallback extends ComponentCallback {
-
- public ExecuteComponentCallback(String behaviorEvent) {
- super(behaviorEvent, false, true);
- }
-
- @Override
- protected void addDefaultComponents(Collection<String> ids) {
- super.addDefaultComponents(ids);
- ids.add(AjaxRendererUtils.THIS);
- }
-
- @Override
- public Object getAttributeValue(UIComponent component) {
- return component.getAttributes().get("execute");
- }
-
- @Override
- protected Object getBehaviorAttributeValue(AjaxClientBehavior behavior) {
- return behavior.getExecute();
- }
- }
-
- private static class RenderComponentCallback extends ComponentCallback {
-
- public RenderComponentCallback(String behaviorEvent) {
- super(behaviorEvent, false, false);
- }
-
- private boolean limitRender = false;
-
- public boolean isLimitRender() {
- return limitRender;
- }
-
- @Override
- protected void doVisit(FacesContext context, UIComponent target,
- AjaxClientBehavior behavior) {
-
- super.doVisit(context, target, behavior);
- limitRender = AjaxRendererUtils.isAjaxLimitRender(target);
- if (behavior != null) {
- limitRender = behavior.isLimitRender();
- }
- }
-
- @Override
- public Object getAttributeValue(UIComponent component) {
- return component.getAttributes().get("render");
- }
-
- @Override
- protected Object getBehaviorAttributeValue(AjaxClientBehavior behavior) {
- return behavior.getRender();
- }
- }
-
//TODO: data table support
- private Collection<String> getAjaxOutputComponentIds(FacesContext facesContext) {
+ private static Collection<String> getAjaxOutputComponentIds(FacesContext
facesContext) {
List<String> ids = new ArrayList<String>();
Collection<AjaxOutput> ajaxOutputComponentsSet =
PartialViewContextAjaxOutputTracker.getAjaxOutputComponentsSet(facesContext);
for (AjaxOutput ajaxOutput : ajaxOutputComponentsSet) {
@@ -273,66 +102,69 @@
}
private void processExecute(PartialViewContext partialViewContext) {
- if (!hasProcessedExecute) {
- hasProcessedExecute = true;
+ if (hasProcessedExecute) {
+ return;
+ }
+ hasProcessedExecute = true;
- FacesContext facesContext = FacesContext.getCurrentInstance();
-
- decodeBehaviorEvent(facesContext);
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ decodeBehaviorEvent(facesContext);
- ExecuteComponentCallback executeCallback = new
ExecuteComponentCallback(behaviorEvent);
-
- boolean visitResult = facesContext.getViewRoot().visitTree(
- createVisitContext(facesContext),
- executeCallback);
+ ComponentCallback executeCallback = new ExecuteComponentCallback(behaviorEvent);
- if (!visitResult) {
- //TODO:
- }
+ boolean visitResult =
facesContext.getViewRoot().visitTree(createVisitContext(facesContext), executeCallback);
+ if (!visitResult) {
+ //TODO:
+ }
- executeAll = executeCallback.isHandleAll();
- if (!executeAll) {
- Collection<String> executeIds = partialViewContext.getExecuteIds();
- executeIds.clear();
+ executeAll = executeCallback.isHandleAll();
+ if (executeAll) {
+ return;
+ }
+
+ Collection<String> executeIds = partialViewContext.getExecuteIds();
+ executeIds.clear();
- if (!executeCallback.isHandleNone()) {
- executeIds.addAll(executeCallback.getComponentIds());
- //TODO ids from wrapped object?
- }
- }
- }
- }
+ if (!executeCallback.isHandleNone()) {
+ executeIds.addAll(executeCallback.getComponentIds());
+ //TODO ids from wrapped object?
+ }
+ }
private void processRender(PartialViewContext partialViewContext) {
FacesContext facesContext = FacesContext.getCurrentInstance();
- if (!partialViewContext.isRenderAll()) {
- RenderComponentCallback renderCallback = new RenderComponentCallback(behaviorEvent);
- boolean visitResult = facesContext.getViewRoot().visitTree(
- createVisitContext(facesContext),
- renderCallback);
-
- if (!visitResult) {
- //TODO:
- }
+ if (partialViewContext.isRenderAll()) {
+ return;
+ }
- boolean renderAll = renderCallback.isHandleAll();
- partialViewContext.setRenderAll(renderAll);
- if (!renderAll) {
- Collection<String> renderIds = partialViewContext.getRenderIds();
- renderIds.clear();
+ RenderComponentCallback renderCallback = new
RenderComponentCallback(behaviorEvent);
+ boolean visitResult = facesContext.getViewRoot().visitTree(
+ createVisitContext(facesContext),
+ renderCallback);
- if (!renderCallback.isHandleNone()) {
- renderIds.addAll(renderCallback.getComponentIds());
+ if (!visitResult) {
+ //TODO:
+ }
- if (!renderCallback.isLimitRender()) {
- Collection<String> ajaxOutputComponentIds =
getAjaxOutputComponentIds(facesContext);
- renderIds.addAll(ajaxOutputComponentIds);
- //TODO ids from wrapped object?
- }
- }
- }
- }
+ boolean renderAll = renderCallback.isHandleAll();
+ partialViewContext.setRenderAll(renderAll);
+ if (renderAll) {
+ return;
+ }
+
+ Collection<String> renderIds = partialViewContext.getRenderIds();
+ renderIds.clear();
+
+ if (!renderCallback.isHandleNone()) {
+ renderIds.addAll(renderCallback.getComponentIds());
+
+ if (!renderCallback.isLimitRender()) {
+ Collection<String> ajaxOutputComponentIds =
getAjaxOutputComponentIds(facesContext);
+ renderIds.addAll(ajaxOutputComponentIds);
+ //TODO ids from wrapped object?
+ }
+ }
}
@Override
Added:
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java
(rev 0)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/RenderComponentCallback.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -0,0 +1,66 @@
+/**
+ * License Agreement.
+ *
+ * Rich Faces - Natural Ajax for Java Server Faces (JSF)
+ *
+ * Copyright (C) 2007 Exadel, Inc.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License version 2.1 as published by the Free Software Foundation.
+ *
+ * This library 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 library; if not, write to the Free Software
+ * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ */
+
+package org.richfaces.context;
+
+import org.ajax4jsf.component.AjaxClientBehavior;
+import org.ajax4jsf.renderkit.AjaxRendererUtils;
+
+import javax.faces.context.FacesContext;
+import javax.faces.component.UIComponent;
+
+/**
+ * @author akolonitsky
+ * @since Oct 13, 2009
+ */
+class RenderComponentCallback extends ComponentCallback {
+
+ RenderComponentCallback(String behaviorEvent) {
+ super(behaviorEvent, false, false);
+ }
+
+ private boolean limitRender = false;
+
+ public boolean isLimitRender() {
+ return limitRender;
+ }
+
+ @Override
+ protected void doVisit(FacesContext context, UIComponent target,
+ AjaxClientBehavior behavior) {
+
+ super.doVisit(context, target, behavior);
+ limitRender = AjaxRendererUtils.isAjaxLimitRender(target);
+ if (behavior != null) {
+ limitRender = behavior.isLimitRender();
+ }
+ }
+
+ @Override
+ public Object getAttributeValue(UIComponent component) {
+ return component.getAttributes().get("render");
+ }
+
+ @Override
+ protected Object getBehaviorAttributeValue(AjaxClientBehavior behavior) {
+ return behavior.getRender();
+ }
+}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/context/SingletonsContext.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -30,42 +30,12 @@
* @since 4.0
*/
public class SingletonsContext {
-
- public static abstract class ContextProvider {
-
- protected final String singletonContextAttributeName;
- protected ContextProvider(String attributeSuffixName) {
- this.singletonContextAttributeName = SingletonsContext.class.getName() + ":"
+ attributeSuffixName;
- }
+ private SingletonsContext() {
+ }
- protected AttributesContext createContext() {
- return new AttributesContext();
- }
+ public static final ContextProvider APPLICATION = new
ContextProvider("Application") {
- protected abstract Map<? super String, Object> getContextMap(FacesContext
facesContext);
-
- protected AttributesContext createAndStoreContext(FacesContext context) {
- AttributesContext instance = createContext();
- getContextMap(context).put(singletonContextAttributeName, instance);
-
- return instance;
- }
-
- public AttributesContext get(FacesContext context) {
- Map<? super String, Object> contextMap = getContextMap(context);
-
- AttributesContext instance = (AttributesContext)
contextMap.get(singletonContextAttributeName);
- if (instance == null) {
- instance = createAndStoreContext(context);
- }
-
- return instance;
- }
- }
-
- public static final ContextProvider APPLICATION = new
ContextProvider("Application") {
-
@Override
protected Map<String, Object> getContextMap(FacesContext facesContext) {
return facesContext.getExternalContext().getApplicationMap();
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractBaseResource.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -38,12 +38,13 @@
import javax.faces.context.FacesContext;
import org.ajax4jsf.resource.InternetResource;
-import org.ajax4jsf.resource.ResourceContext;
import org.richfaces.context.SingletonsContext;
import org.richfaces.log.RichfacesLogger;
import org.richfaces.util.Util;
import org.slf4j.Logger;
+import static org.richfaces.resource.ResourceUtils.*;
+
/**
* @author Nick Belaevski
* @since 4.0
@@ -59,17 +60,13 @@
private String version;
private Date lastModified = null;
-
- public AbstractBaseResource() {
+
+ protected AbstractBaseResource() {
super();
this.setResourceName(getClass().getName());
}
- /**
- * @param resourceContext current {@link ResourceContext}
- * @return Returns the contentLength.
- */
//TODO remove FacesContext argument?
protected int getContentLength(FacesContext context) {
return -1;
@@ -77,7 +74,7 @@
/**
* <b>IMPORTANT:</b> this method returned TTL in RF 3.x, now it returns
expiration time
- * @return Returns the expired.
+ * @return Returns the expired.
*/
protected Date getExpires(FacesContext context) {
return null;
@@ -86,70 +83,81 @@
protected int getTimeToLive(FacesContext context) {
return 0;
}
-
- /**
- * @param resourceContext current {@link ResourceContext}
- * @return Returns the lastModified.
- */
- //TODO optimize/review?
- protected Date getLastModified(FacesContext context) {
- if (lastModified == null) {
- Class<? extends AbstractBaseResource> thisClass = getClass();
- ClassLoader classLoader = thisClass.getClassLoader();
- if (classLoader == null) {
- classLoader = ClassLoader.getSystemClassLoader();
- }
-
- if (classLoader != null) {
- URL classResource = classLoader.getResource(thisClass.getName().replace('.',
'/') + ".class");
- if (classResource != null) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Located source for the resource class:
{0}", classResource));
- }
- URLConnection connection;
- try {
- connection = classResource.openConnection();
- connection.setUseCaches(false);
- long classLastModifiedDate = connection.getLastModified();
- if (classLastModifiedDate > 0) {
- lastModified = new Date(classLastModifiedDate);
+ /**
+ * TODO optimize/review?
+ * @return Returns the lastModified.
+ */
+ @Override
+ protected Date getLastModified(FacesContext context) {
+ if (lastModified == null) {
+ lastModified = getLastModifiedBySource();
+ }
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Last source modification date is:
{0,date}", lastModified));
- }
- }
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- } else {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("Source for the resource class has not been located");
- }
- }
- }
- }
+ //TODO - originally lastModified was set during resource creation.
+ //as resources can be managed beans this approach does not seem good
+ if (lastModified == null) {
+ lastModified = (Date) SingletonsContext.APPLICATION.get(context).
+ getAttribute(ResourceHandlerImpl.HANDLER_START_TIME_ATTRIBUTE);
- //TODO - originally lastModified was set during resource creation.
- //as resources can be managed beans this approach does not seem good
- if (lastModified == null) {
- lastModified = (Date) SingletonsContext.APPLICATION.get(context).
- getAttribute(ResourceHandlerImpl.HANDLER_START_TIME_ATTRIBUTE);
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(MessageFormat.format("Using resource handler start time
as last modified date: {0,date,dd MMM yyyy HH:mm:ss zzz}", lastModified));
+ }
+ }
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug(MessageFormat.format("Using resource handler start time as last
modified date: {0,date,dd MMM yyyy HH:mm:ss zzz}", lastModified));
- }
- }
-
- return lastModified;
- }
+ return lastModified;
+ }
- /**
- * @param resourceContext current {@link ResourceContext}
+ private Date getLastModifiedBySource() {
+ ClassLoader classLoader = getClassLoader();
+ if (classLoader == null) {
+ return null;
+ }
+
+ URL classResource =
classLoader.getResource(getClass().getName().replace('.', '/') +
".class");
+ if (classResource != null) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(MessageFormat.format("Located source for the resource
class: {0}", classResource));
+ }
+
+ try {
+ URLConnection connection = classResource.openConnection();
+ connection.setUseCaches(false);
+ long classLastModifiedDate = connection.getLastModified();
+ if (classLastModifiedDate > 0) {
+ lastModified = new Date(classLastModifiedDate);
+
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug(MessageFormat.format("Last source modification
date is: {0,date}", lastModified));
+ }
+ }
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ } else {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Source for the resource class has not been
located");
+ }
+ }
+
+ return null;
+ }
+
+ private ClassLoader getClassLoader() {
+ Class<? extends AbstractBaseResource> thisClass = getClass();
+ ClassLoader classLoader = thisClass.getClassLoader();
+ if (classLoader == null) {
+ classLoader = ClassLoader.getSystemClassLoader();
+ }
+ return classLoader;
+ }
+
+ /**
* @return Returns the cacheable.
*/
- public boolean isCacheable(FacesContext context) {
+ @Override
+ public boolean isCacheable(FacesContext context) {
return cacheable;
}
@@ -157,18 +165,19 @@
this.cacheable = cacheable;
}
- protected String getEntityTag(FacesContext context) {
- int contentLength = getContentLength(context);
- Date lastModified = getLastModified(context);
-
- if (contentLength >= 0 && lastModified != null) {
- return ResourceUtils.formatWeakTag(contentLength + "-" +
lastModified.getTime());
- } else {
- return null;
- }
- }
+ @Override
+ protected String getEntityTag(FacesContext context) {
+ int contentLength = getContentLength(context);
+ Date lastModified = getLastModified(context);
- @Override
+ if (contentLength < 0 || lastModified == null) {
+ return null;
+ }
+
+ return ResourceUtils.formatWeakTag(contentLength + "-" +
lastModified.getTime());
+ }
+
+ @Override
public abstract InputStream getInputStream();
@Override
@@ -241,24 +250,22 @@
headers.put("Last-Modified", Util.formatHttpDate(lastModified));
}
- boolean cacheable = isCacheable(facesContext);
-
- if (cacheable) {
+ if (isCacheable(facesContext)) {
long currentTime = getCurrentTime();
- String formattedExpireDate = null;
+ String formattedExpireDate;
long maxAge = getTimeToLive(facesContext);
if (maxAge > 0) {
- formattedExpireDate = Util.formatHttpDate(currentTime + maxAge * 1000L);
+ formattedExpireDate = Util.formatHttpDate(currentTime + secondToMillis(maxAge));
} else {
Date expired = getExpires(facesContext);
if (expired != null) {
formattedExpireDate = Util.formatHttpDate(expired);
- maxAge = (expired.getTime() - currentTime) / 1000L;
+ maxAge = millisToSecond(expired.getTime() - currentTime);
} else {
maxAge = InternetResource.DEFAULT_TTL;
- formattedExpireDate = Util.formatHttpDate(currentTime + maxAge * 1000L);
+ formattedExpireDate = Util.formatHttpDate(currentTime + secondToMillis(maxAge));
}
}
@@ -293,68 +300,73 @@
return headers;
}
- @Override
- public URL getURL() {
- // TODO Auto-generated method stub
- try {
- return new URL(URL_PROTOCOL, null, -1, getResourceName(), new URLStreamHandler() {
-
- @Override
- protected URLConnection openConnection(URL u) throws IOException {
+ @Override
+ public URL getURL() {
+ try {
+ return new URL(URL_PROTOCOL, null, -1, getResourceName(), new
MyURLStreamHandler());
+ } catch (MalformedURLException e) {
+ throw new FacesException(e.getLocalizedMessage(), e);
+ }
+ }
- return new URLConnection(u) {
-
- @Override
- public void connect() throws IOException {
- }
-
- @Override
- public int getContentLength() {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- return AbstractBaseResource.this.getContentLength(facesContext);
- }
-
- @Override
- public String getContentType() {
- return AbstractBaseResource.this.getContentType();
- }
-
- @Override
- public long getExpiration() {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- long ttl = AbstractBaseResource.this.getTimeToLive(facesContext);
- if (ttl > 0) {
- return System.currentTimeMillis() + ttl * 1000;
- }
+ private class MyURLStreamHandler extends URLStreamHandler {
- Date date = AbstractBaseResource.this.getExpires(facesContext);
- if (date != null) {
- return date.getTime();
- }
-
- return System.currentTimeMillis() + InternetResource.DEFAULT_TTL * 1000;
- }
-
- @Override
- public long getLastModified() {
- FacesContext facesContext = FacesContext.getCurrentInstance();
- Date date = AbstractBaseResource.this.getLastModified(facesContext);
- if (date != null) {
- return date.getTime();
- }
+ @Override
+ protected URLConnection openConnection(URL u) throws IOException {
+ return new MyURLConnection(u);
+ }
+ }
- return 0;
- }
-
- @Override
- public InputStream getInputStream() throws IOException {
- return AbstractBaseResource.this.getInputStream();
- }
- };
- }
- });
- } catch (MalformedURLException e) {
- throw new FacesException(e.getLocalizedMessage(), e);
- }
- }
+ private class MyURLConnection extends URLConnection {
+ MyURLConnection(URL u) {
+ super(u);
+ }
+
+ @Override
+ public void connect() throws IOException {
+ }
+
+ @Override
+ public int getContentLength() {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ return AbstractBaseResource.this.getContentLength(facesContext);
+ }
+
+ @Override
+ public String getContentType() {
+ return AbstractBaseResource.this.getContentType();
+ }
+
+ @Override
+ public long getExpiration() {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ long ttl = AbstractBaseResource.this.getTimeToLive(facesContext);
+ if (ttl > 0) {
+ return System.currentTimeMillis() + secondToMillis(ttl);
+ }
+
+ Date date = AbstractBaseResource.this.getExpires(facesContext);
+ if (date != null) {
+ return date.getTime();
+ }
+
+ return System.currentTimeMillis() +
secondToMillis(InternetResource.DEFAULT_TTL);
+ }
+
+ @Override
+ public long getLastModified() {
+ FacesContext facesContext = FacesContext.getCurrentInstance();
+ Date date = AbstractBaseResource.this.getLastModified(facesContext);
+ if (date != null) {
+ return date.getTime();
+ }
+
+ return 0;
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ return AbstractBaseResource.this.getInputStream();
+ }
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AbstractCacheableResource.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -37,92 +37,102 @@
*/
public abstract class AbstractCacheableResource extends Resource {
- private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
+ private static final Logger LOGGER = RichfacesLogger.RESOURCE.getLogger();
- protected abstract Date getLastModified(FacesContext context);
+ protected abstract Date getLastModified(FacesContext context);
- public abstract boolean isCacheable(FacesContext context);
-
- protected abstract String getEntityTag(FacesContext context);
-
- //TODO add getExpired(FacesContext) for HTTP matching headers?
-
- private Boolean userCopyIsActual(Date lastModified, Date modifiedCondition) {
- if (modifiedCondition == null) {
- return null;
- }
-
- if (lastModified == null) {
- return Boolean.FALSE;
- }
-
- // 1000 ms due to round
- // modification
- // time to seconds.
- return Boolean.valueOf((lastModified.getTime() - modifiedCondition.getTime()) <=
1000);
- }
-
- protected Boolean matchesLastModified(FacesContext context) {
- ExternalContext externalContext = context.getExternalContext();
- Map<String, String> requestHeaderMap = externalContext.getRequestHeaderMap();
+ public abstract boolean isCacheable(FacesContext context);
- String modifiedCondition = requestHeaderMap.get("If-Modified-Since");
- return userCopyIsActual(getLastModified(context),
Util.parseHttpDate(modifiedCondition));
- }
-
- protected Boolean matchesEntityTag(FacesContext context) {
- ExternalContext externalContext = context.getExternalContext();
- Map<String, String> requestHeaderMap = externalContext.getRequestHeaderMap();
- String matchHeaderValue = requestHeaderMap.get("If-None-Match");
+ protected abstract String getEntityTag(FacesContext context);
- if (matchHeaderValue == null) {
- //no need to check
- return null;
- } else {
- String resourceEntityTag = getEntityTag(context);
- if (resourceEntityTag != null) {
- return ResourceUtils.matchTag(resourceEntityTag, matchHeaderValue);
- } else {
- return Boolean.FALSE;
- }
- }
- }
-
- @Override
- public boolean userAgentNeedsUpdate(FacesContext context) {
- if (!isCacheable(context)) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("User agent cache check: resource is not cacheable");
- }
-
- return true;
- }
+ //TODO add getExpired(FacesContext) for HTTP matching headers?
- Boolean matchesEntityTag = matchesEntityTag(context);
- if (Boolean.FALSE.equals(matchesEntityTag)) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("User agent cache check: entity tags don't match");
- }
+ private static boolean isUserCopyActual(Date lastModified, Date modifiedCondition) {
+ // 1000 ms due to round modification time to seconds.
+ return (lastModified.getTime() - modifiedCondition.getTime()) <= 1000;
+ }
- return true;
- }
+ @Deprecated
+ protected Boolean isMatchesLastModified(FacesContext context) {
+ ExternalContext externalContext = context.getExternalContext();
+ Map<String, String> requestHeaderMap =
externalContext.getRequestHeaderMap();
+ String modifiedCondition = requestHeaderMap.get("If-Modified-Since");
- Boolean matchesLastModified = matchesLastModified(context);
- if (Boolean.FALSE.equals(matchesLastModified)) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("User agent cache check: resource was modified since the last
request");
- }
- return true;
- }
-
- if (matchesLastModified == null && matchesEntityTag == null) {
- if (LOGGER.isDebugEnabled()) {
- LOGGER.debug("User agent cache check: no cache information was provided in
request");
- }
- return true;
- }
-
- return false;
- }
-
+ if (modifiedCondition == null) {
+ return null;
+ }
+
+ return isMatchesLastModified(context, modifiedCondition);
+ }
+
+ protected boolean isMatchesLastModified(FacesContext context, String
modifiedCondition) {
+ Date lastModified = getLastModified(context);
+ if (lastModified == null) {
+ return false;
+ }
+
+ return isUserCopyActual(lastModified, Util.parseHttpDate(modifiedCondition));
+ }
+
+ @Deprecated
+ protected Boolean isMatchesEntityTag(FacesContext context) {
+ ExternalContext externalContext = context.getExternalContext();
+ Map<String, String> requestHeaderMap =
externalContext.getRequestHeaderMap();
+ String matchHeaderValue = requestHeaderMap.get("If-None-Match");
+
+ if (matchHeaderValue == null) {
+ return null;
+ }
+
+ return isMatchesEntityTag(context, matchHeaderValue);
+ }
+ protected boolean isMatchesEntityTag(FacesContext context, String matchHeaderValue)
{
+ String resourceEntityTag = getEntityTag(context);
+ if (resourceEntityTag == null) {
+ return false;
+ }
+
+ return ResourceUtils.matchTag(resourceEntityTag, matchHeaderValue);
+ }
+
+ @Override
+ public boolean userAgentNeedsUpdate(FacesContext context) {
+ if (!isCacheable(context)) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("User agent cache check: resource is not
cacheable");
+ }
+
+ return true;
+ }
+
+ ExternalContext externalContext = context.getExternalContext();
+ Map<String, String> requestHeaderMap =
externalContext.getRequestHeaderMap();
+ String modifiedCondition = requestHeaderMap.get("If-Modified-Since");
+ String matchHeaderValue = requestHeaderMap.get("If-None-Match");
+
+ if (modifiedCondition == null && matchHeaderValue == null) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("User agent cache check: no cache information was
provided in request");
+ }
+ return true;
+ }
+
+ if (matchHeaderValue != null && !isMatchesEntityTag(context,
matchHeaderValue)) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("User agent cache check: entity tags don't
match");
+ }
+
+ return true;
+ }
+
+ if (modifiedCondition != null && !isMatchesLastModified(context,
modifiedCondition)) {
+ if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("User agent cache check: resource was modified since
the last request");
+ }
+ return true;
+ }
+
+ return false;
+ }
+
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/AnimatedTestResource.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -21,10 +21,7 @@
package org.richfaces.resource;
-import java.awt.Color;
-import java.awt.GradientPaint;
-import java.awt.Graphics2D;
-import java.awt.GraphicsEnvironment;
+import java.awt.*;
import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
@@ -46,11 +43,11 @@
public class AnimatedTestResource extends TestResource2 {
- private int FRAMES_COUNT = 10;
+ private static final int FRAMES_COUNT = 10;
- private int delayTime = 500;
-
- private ImageWriter getImageWriter() {
+ private static final int DELAY_TIME = 50;
+
+ private static ImageWriter getImageWriter() {
ImageWriter result = null;
Iterator<ImageWriter> imageWriters =
ImageIO.getImageWritersByFormatName("gif");
@@ -66,18 +63,18 @@
private static Node getOrCreateChild(Node root, String name) {
Node result = null;
-
- for (Node node = root.getFirstChild(); node != null && result == null; node
= node.getNextSibling()) {
+
+ for (Node node = root.getFirstChild(); node != null && result == null;
node = node.getNextSibling()) {
if (name.equals(node.getNodeName())) {
- result = node;
+ result = node;
}
}
-
- if (result == null) {
- result = new IIOMetadataNode(name);
- root.appendChild(result);
- }
-
+
+ if (result == null) {
+ result = new IIOMetadataNode(name);
+ root.appendChild(result);
+ }
+
return result;
}
@@ -89,7 +86,8 @@
@Override
public InputStream getInputStream() {
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
- BufferedImage image = new BufferedImage(dimension.width, dimension.height,
ColorSpace.TYPE_RGB);
+ Dimension dimension = getDimension();
+ BufferedImage image = new BufferedImage(dimension.width, dimension.height,
ColorSpace.TYPE_RGB);
Graphics2D g2d = environment.createGraphics(image);
ImageWriter sequenceCapableImageWriter = getImageWriter();
@@ -98,7 +96,7 @@
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
- ImageOutputStream imageOutputStream = null;;
+ ImageOutputStream imageOutputStream = null;
try {
imageOutputStream = ImageIO.createImageOutputStream(baos);
@@ -116,8 +114,7 @@
graphicsControlExtensionNode.setAttribute("disposalMethod",
"none");
graphicsControlExtensionNode.setAttribute("userInputFlag",
"FALSE");
graphicsControlExtensionNode.setAttribute("transparentColorFlag",
"FALSE");
- graphicsControlExtensionNode.setAttribute("delayTime",
- Integer.toString(delayTime / 10));
+ graphicsControlExtensionNode.setAttribute("delayTime",
Integer.toString(DELAY_TIME));
graphicsControlExtensionNode.setAttribute("transparentColorIndex",
"0");
boolean loopContinuously = false;
@@ -135,8 +132,8 @@
sequenceCapableImageWriter.prepareWriteSequence(null);
- for (int i = 1; i <= FRAMES_COUNT; i++) {
- g2d.setPaint(new GradientPaint(0, i * dimension.height / FRAMES_COUNT, Color.WHITE,
0, dimension.height, color));
+ for (int i = 1; i <= FRAMES_COUNT; i++) {
+ g2d.setPaint(new GradientPaint(0, i * dimension.height / FRAMES_COUNT, Color.WHITE,
0, dimension.height, getColor()));
g2d.fillRect(0, 0, dimension.width, dimension.height);
sequenceCapableImageWriter.writeToSequence(new IIOImage(image, null, imageMetaData),
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/CachedResourceImpl.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -41,6 +41,8 @@
import org.richfaces.util.Util;
import org.slf4j.Logger;
+import static org.richfaces.resource.ResourceUtils.*;
+
/**
* @author Nick Belaevski
* @since 4.0
@@ -67,41 +69,45 @@
private Date lastModified;
- //serves only to define server cache entry expiration time only
- //browser cache expiration is controlled by stored HTTP headers value
+ /***
+ * serves only to define server cache entry expiration time only
+ * browser cache expiration is controlled by stored HTTP headers value
+ */
private Date expired;
private void initializeFromHeaders() {
this.entityTag = null;
this.lastModified = null;
-
- //this.setContentType(null);
-
this.expired = null;
Date expiredFromHeader = null;
//TODO what if maxAge = 0 in header?
int maxAge = 0;
-
+
for (Entry<String, String> headerEntry: headers.entrySet()) {
String headerKey = headerEntry.getKey().toLowerCase(Locale.US);
if ("etag".equals(headerKey)) {
this.entityTag = headerEntry.getValue();
- } else if ("last-modified".equals(headerKey)) {
+ }
+
+ if ("last-modified".equals(headerKey)) {
this.lastModified = Util.parseHttpDate(headerEntry.getValue());
- } else if ("expires".equals(headerKey)) {
+ }
+
+ if ("expires".equals(headerKey)) {
expiredFromHeader = Util.parseHttpDate(headerEntry.getValue());
- } else if ("cache-control".equals(headerKey)) {
+ }
+
+ if ("cache-control".equals(headerKey)) {
String[] values = headerEntry.getValue().split(",");
for (String value : values) {
Matcher matcher = MAX_AGE.matcher(value.trim());
if (matcher.find()) {
- boolean isSMaxAge = (matcher.group(SMAX_AGE_GROUP) != null);
- if (maxAge <= 0 || isSMaxAge /* s-maxage overrides max-age */) {
+ boolean isSMaxAge = matcher.group(SMAX_AGE_GROUP) != null;
+ if (maxAge <= 0 || isSMaxAge) { // s-maxage overrides max-age
try {
- maxAge = Integer.parseInt(matcher.group(MAX_AGE_VALUE_GROUP)) *
- 1000 /* maxAge is in seconds - convert to milliseconds */;
+ maxAge = (int)
secondToMillis(Integer.parseInt(matcher.group(MAX_AGE_VALUE_GROUP)));
} catch (NumberFormatException e) {
// TODO: handle exception
e.printStackTrace();
@@ -109,9 +115,7 @@
}
}
}
- }/* else if ("content-type".equals(headerKey)) {
- this.setContentType(headerEntry.getValue());
- }*/
+ }
}
long currentTime = getCurrentTime();
@@ -131,7 +135,7 @@
return System.currentTimeMillis();
}
- private ByteBuffer readContent(InputStream is) throws IOException {
+ private static ByteBuffer readContent(InputStream is) throws IOException {
if (is == null) {
throw new NullPointerException("Resource input stream is null");
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/DefaultResourceCodec.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -23,7 +23,7 @@
import org.richfaces.util.Util;
-class DefaultResourceCodec implements ResourceCodec {
+final class DefaultResourceCodec implements ResourceCodec {
private static final ResourceCodec CODEC = new DefaultResourceCodec();
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceHandlerImpl.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -99,13 +99,11 @@
}
private void initializeCache(FacesContext facesContext) {
- CacheManager cacheManager = CacheManager.getInstance();
Map<?,?> envMap = facesContext.getExternalContext().getInitParameterMap();
- cacheManager.createCache(RESOURCE_CACHE_NAME, envMap);
- cache = cacheManager.getCache(RESOURCE_CACHE_NAME);
+ cache = CacheManager.getInstance().getNewCache(RESOURCE_CACHE_NAME, envMap);
}
- private void markStartTime(FacesContext facesContext) {
+ private static void markStartTime(FacesContext facesContext) {
AttributesContext applicationContext =
SingletonsContext.APPLICATION.get(facesContext);
applicationContext.setAttribute(HANDLER_START_TIME_ATTRIBUTE, new Date());
}
@@ -134,7 +132,7 @@
return resourceCodec;
}
- protected String getResourceKey(FacesContext context) {
+ protected static String getResourceKey(FacesContext context) {
String resourceName = Util.decodeResourceURL(context);
if (resourceName != null) {
if (resourceName.startsWith(RICHFACES_RESOURCE_IDENTIFIER)) {
@@ -149,24 +147,23 @@
}
protected boolean isThisHandlerResourceRequest(FacesContext context) {
- Boolean resourceRequest = BooleanRequestStateVariable.RESOURCE_REQUEST.get(context);
+ Boolean resourceRequest = BooleanRequestStateVariable.ResourceRequest.get(context);
if (resourceRequest == null) {
String resourceKey = getResourceKey(context);
//TODO handle exclusions
- resourceRequest = (resourceKey != null && resourceKey.length() > 0) ?
Boolean.TRUE : Boolean.FALSE;
- BooleanRequestStateVariable.RESOURCE_REQUEST.set(context, resourceRequest);
+ resourceRequest = resourceKey != null && resourceKey.length() > 0;
+ BooleanRequestStateVariable.ResourceRequest.set(context, resourceRequest);
- if (LOGGER.isDebugEnabled()) {
- if (Boolean.TRUE.equals(resourceRequest)) {
- LOGGER.debug(MessageFormat.format("Resource request detected: {0}",
resourceKey));
- }
+ if (LOGGER.isDebugEnabled() && resourceRequest) {
+ LOGGER.debug(MessageFormat.format("Resource request detected: {0}",
resourceKey));
}
}
- return resourceRequest.booleanValue();
+ return resourceRequest;
}
- public boolean isResourceRequest(FacesContext context) {
+ @Override
+ public boolean isResourceRequest(FacesContext context) {
return isThisHandlerResourceRequest(context) ||
defaultHandler.isResourceRequest(context);
}
@@ -184,7 +181,7 @@
return resource;
}
- private void sendNotModified(FacesContext context) {
+ private static void sendNotModified(FacesContext context) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("User agent has actual resource copy - sending 304 status
code");
}
@@ -214,11 +211,12 @@
logResourceProblem(context, null, "Resource {0} was not found",
resourceData);
}
- private void sendResourceNotFound(FacesContext context) {
+ private static void sendResourceNotFound(FacesContext context) {
context.getExternalContext().setResponseStatus(HttpServletResponse.SC_NOT_FOUND);
}
- public void handleResourceRequest(FacesContext context) throws IOException {
+ @Override
+ public void handleResourceRequest(FacesContext context) throws IOException {
if (isThisHandlerResourceRequest(context)) {
String resourceKey = getResourceKey(context);
@@ -382,7 +380,7 @@
}
}
- protected boolean isResourceExists(String resourceName) {
+ protected static boolean isResourceExists(String resourceName) {
boolean result = false;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
if (contextClassLoader != null) {
@@ -435,14 +433,15 @@
return resource;
}
- public Resource createResource(String resourceName, String libraryName,
+ @Override
+ public Resource createResource(String resourceName, String libraryName,
String contentType) {
- Resource result = null;
-
+ Resource result;
+
if (resourceName != null && (libraryName == null || libraryName.length() == 0)
&& isResourceExists(resourceName)) {
-
+
result = createHandlerDependentResource(resourceName);
} else {
result = defaultHandler.createResource(resourceName, libraryName, contentType);
@@ -451,20 +450,24 @@
return result;
}
- public Resource createResource(String resourceName, String libraryName) {
+ @Override
+ public Resource createResource(String resourceName, String libraryName) {
return createResource(resourceName, libraryName, null);
}
- public Resource createResource(String resourceName) {
+ @Override
+ public Resource createResource(String resourceName) {
return createResource(resourceName, null, null);
}
- public String getRendererTypeForResourceName(String resourceName) {
+ @Override
+ public String getRendererTypeForResourceName(String resourceName) {
//TODO add support for dynamic resources
return defaultHandler.getRendererTypeForResourceName(resourceName);
}
- public boolean libraryExists(String libraryName) {
+ @Override
+ public boolean libraryExists(String libraryName) {
return defaultHandler.libraryExists(libraryName);
}
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/ResourceUtils.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -29,7 +29,7 @@
* @author Nick Belaevski
* @since 4.0
*/
-public class ResourceUtils {
+public final class ResourceUtils {
private ResourceUtils() {}
@@ -37,6 +37,8 @@
private static final Pattern ETAG_PATTERN = Pattern.compile("(?:W/)?\"("
+ QUOTED_STRING_REGEX + ")\"(?:,\\s*)?");
+ private static final long MILLISECOND_IN_SECOND = 1000L;
+
public static String formatWeakTag(String eTag) {
String formattedTag = formatTag(eTag);
if (formattedTag == null) {
@@ -52,29 +54,28 @@
}
if (!eTag.matches(QUOTED_STRING_REGEX)) {
- //TODO warn
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("tag must matches to regexp '" +
QUOTED_STRING_REGEX + '\'');
}
- return "\"" + eTag + "\"";
+ return '\"' + eTag + '\"';
}
public static boolean matchTag(String eTag, String eTagHeaderValue) {
if (eTag == null || eTagHeaderValue == null) {
- throw new NullPointerException();
+ throw new IllegalArgumentException("tag and tagHeaderValue must be not
null");
}
Matcher eTagMatcher = ETAG_PATTERN.matcher(eTag);
if (!eTagMatcher.find()) {
throw new IllegalArgumentException();
- } else {
- eTag = eTagMatcher.group(1);
}
-
-
+
+ String tag = eTagMatcher.group(1);
+
+
Matcher eTagHeaderMatcher = ETAG_PATTERN.matcher(eTagHeaderValue);
while (eTagHeaderMatcher.find()) {
- if (eTag.equals(eTagHeaderMatcher.group(1))) {
+ if (tag.equals(eTagHeaderMatcher.group(1))) {
return true;
}
}
@@ -82,4 +83,11 @@
return false;
}
+ public static long millisToSecond(long millisecond) {
+ return millisecond / MILLISECOND_IN_SECOND;
+ }
+
+ public static long secondToMillis(long second) {
+ return second * MILLISECOND_IN_SECOND;
+ }
}
Deleted: root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -1,112 +0,0 @@
-/**
- * License Agreement.
- *
- * Rich Faces - Natural Ajax for Java Server Faces (JSF)
- *
- * Copyright (C) 2007 Exadel, Inc.
- *
- * This library is free software; you can redistribute it and/or
- * modify it under the terms of the GNU Lesser General Public
- * License version 2.1 as published by the Free Software Foundation.
- *
- * This library 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 library; if not, write to the Free Software
- * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
- */
-
-package org.richfaces.resource;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.UnsupportedEncodingException;
-
-import javax.faces.FacesException;
-import javax.faces.component.StateHolder;
-import javax.faces.context.FacesContext;
-
-import org.richfaces.VersionBean;
-import org.richfaces.VersionBean.Version;
-
-public class TestResource extends AbstractBaseResource implements StateHolder {
-
- private String filePath;
-
- @Override
- public String getContentType() {
- return "image/png";
- }
-
- @Override
- protected int getContentLength(FacesContext context) {
- return (int) new File(filePath).length();
- }
-
- @Override
- public InputStream getInputStream() {
- try {
- return new FileInputStream(filePath);
- } catch (FileNotFoundException e) {
- throw new FacesException(e.getLocalizedMessage(), e);
- }
- }
-
- @Override
- public String getVersion() {
- Version version = new VersionBean().getVersion();
- return version.getMajor() + "." + version.getMinor() + "." +
version.getRevision();
- }
-
- protected void writeState(ByteArrayOutputStream baos) {
- try {
- baos.write("c:\\tmp\\test.png".getBytes("US-ASCII"));
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- protected void readState(ByteArrayInputStream bais) {
- int available = bais.available();
- byte[] bs = new byte[available];
- try {
- bais.read(bs);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- try {
- filePath = new String(bs, "US-ASCII");
- } catch (UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- public Object saveState(FacesContext context) {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- writeState(baos);
- return baos.toByteArray();
- }
-
- public void restoreState(FacesContext context, Object state) {
- ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) state);
- readState(bais);
- }
-
- public boolean isTransient() {
- return false;
- }
-
- public void setTransient(boolean newTransientValue) {
- }
-}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/resource/TestResource2.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -38,9 +38,13 @@
public class TestResource2 extends Java2Dresource {
- protected Color color;
+ private static final int MASK_FOR_COLOR_WITHOUT_ALPHA_CHANNEL = 0x00FFFFFF;
+
+ private Color color;
- public TestResource2() {
+ private Dimension dimension = new Dimension(20, 150);
+
+ public TestResource2() {
super(ImageType.PNG);
FacesContext context = FacesContext.getCurrentInstance();
Skin skin = SkinFactory.getInstance().getSkin(context);
@@ -48,8 +52,6 @@
this.color = HtmlColor.decode(parameter.toString());
}
- protected Dimension dimension = new Dimension(20, 150);
-
@Override
protected void paint(Graphics2D graphics2d, Dimension dim) {
super.paint(graphics2d, dim);
@@ -73,10 +75,14 @@
@Override
public String getEntityTag(FacesContext context) {
- return ResourceUtils.formatWeakTag(Integer.toHexString(color.getRGB() &
0xFFFFFF));
+ return ResourceUtils.formatWeakTag(getColorWitoutAlphaChanel());
}
-
- @Override
+
+ private String getColorWitoutAlphaChanel() {
+ return Integer.toHexString(color.getRGB() &
MASK_FOR_COLOR_WITHOUT_ALPHA_CHANNEL);
+ }
+
+ @Override
public String getVersion() {
return VersionBean._version.getResourceVersion();
}
@@ -88,4 +94,12 @@
public Dimension getDimension() {
return dimension;
}
+
+ public Color getColor() {
+ return color;
+ }
+
+ public void setColor(Color color) {
+ this.color = color;
+ }
}
Modified:
root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java
===================================================================
---
root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/main/java/org/richfaces/util/RequestStateManager.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -39,9 +39,9 @@
//TODO remove this stuff
public static enum BooleanRequestStateVariable {
- LEGACY_RESOURCE_REQUEST("org.richfaces.LEGACY_RESOURCE_REQUEST"),
+ LegacyResourceRequest("org.richfaces.LEGACY_RESOURCE_REQUEST"),
- RESOURCE_REQUEST("org.richfaces.RESOURCE_REQUEST");
+ ResourceRequest("org.richfaces.RESOURCE_REQUEST");
private String attributeName;
@@ -56,7 +56,7 @@
public void set(FacesContext context, Boolean value) {
RequestStateManager.set(context, this.attributeName, value);
}
- };
+ }
@SuppressWarnings("unchecked")
@@ -101,9 +101,9 @@
Map<String, Object> stateMap = getStateMap(context, false);
if (stateMap != null) {
return stateMap.get(key);
- } else {
- return null;
}
+
+ return null;
}
public static void set(FacesContext context, String key, Object value) {
Modified: root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java
===================================================================
--- root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java 2009-10-21
19:40:42 UTC (rev 15744)
+++ root/framework/trunk/impl/src/main/java/org/richfaces/util/Util.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -41,15 +41,7 @@
package org.richfaces.util;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.io.StreamCorruptedException;
-import java.io.UnsupportedEncodingException;
+import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
@@ -79,29 +71,30 @@
* @author Nick Belaevski
* @since 4.0
*/
-public class Util {
+public final class Util {
- private static final Logger resourceLogger = RichfacesLogger.RESOURCE.getLogger();
-
- private Util() {}
+ private static final Logger RESOURCE_LOGGER = RichfacesLogger.RESOURCE.getLogger();
- /* HTTP Date format required by the HTTP/1.1 RFC */
+ private Util() {
+ }
+
+ /* HTTP Date format required by the HTTP/1.1 RFC */
private static final String RFC1123_DATE_PATTERN = "EEE, dd MMM yyyy HH:mm:ss
zzz";
-
+
private static final SimpleDateFormat RFC1123_DATE_FORMATTER;
-
+
static {
- SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US);
- format.setTimeZone(TimeZone.getTimeZone("GMT"));
+ SimpleDateFormat format = new SimpleDateFormat(RFC1123_DATE_PATTERN, Locale.US);
+ format.setTimeZone(TimeZone.getTimeZone("GMT"));
- RFC1123_DATE_FORMATTER = format;
+ RFC1123_DATE_FORMATTER = format;
}
-
+
public static String getMappingForRequest(FacesContext context) {
ExternalContext externalContext = context.getExternalContext();
-
- String servletPath = externalContext.getRequestServletPath();
+ String servletPath = externalContext.getRequestServletPath();
+
if (servletPath == null) {
return null;
}
@@ -112,265 +105,259 @@
String pathInfo = externalContext.getRequestPathInfo();
if (pathInfo != null) {
- return servletPath;
+ return servletPath;
}
-
+
int idx = servletPath.lastIndexOf('.');
if (idx < 0) {
return servletPath;
} else {
return servletPath.substring(idx);
}
- }
-
+ }
+
public static Date parseHttpDate(String s) {
- Date result = null;
-
- if (s != null) {
- try {
- result = (Date) ((Format) RFC1123_DATE_FORMATTER.clone()).parseObject(s);
- } catch (ParseException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- return result;
+ Date result = null;
+
+ if (s != null) {
+ try {
+ result = (Date) ((Format)
RFC1123_DATE_FORMATTER.clone()).parseObject(s);
+ } catch (ParseException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ return result;
}
-
+
public static String formatHttpDate(Object object) {
- if (object != null) {
- return ((Format) RFC1123_DATE_FORMATTER.clone()).format(object);
- } else {
- return null;
- }
+ if (object != null) {
+ return ((Format) RFC1123_DATE_FORMATTER.clone()).format(object);
+ } else {
+ return null;
+ }
}
-
+
//TODO codec have settings
private static final Codec CODEC = new Codec();
-
- private static final String DATA_SEPARATOR = "/DATA/";
- private static final String DATA_BYTES_SEPARATOR = "/DATB/";
- private static final String VERSION_SEPARATOR = "/VER";
- private static final Pattern DATA_SEPARATOR_PATTERN = Pattern
- .compile("/DAT(A|B)/([^/]*)");
+ private static final String DATA_SEPARATOR = "/DATA/";
+ private static final String DATA_BYTES_SEPARATOR = "/DATB/";
+ private static final String VERSION_SEPARATOR = "/VER";
- //index of capturing group denoting data type encoded
- private static final int DATA_SEPARATOR_TYPE_GROUP_INDEX = 1;
+ private static final Pattern DATA_SEPARATOR_PATTERN = Pattern
+ .compile("/DAT(A|B)/([^/]*)");
- //index of capturing group denoting version
- private static final int DATA_SEPARATOR_DATA_GROUP_INDEX = 2;
-
- protected static byte[] encrypt(byte[] src) {
- try {
- Deflater compressor = new Deflater(Deflater.BEST_SPEED);
- byte[] compressed = new byte[src.length + 100];
- compressor.setInput(src);
- compressor.finish();
- int totalOut = compressor.deflate(compressed);
- byte[] zipsrc = new byte[totalOut];
- System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
- compressor.end();
- return CODEC.encode(zipsrc);
- } catch (Exception e) {
- throw new FacesException("Error encode resource data", e);
- }
- }
+ //index of capturing group denoting data type encoded
+ private static final int DATA_SEPARATOR_TYPE_GROUP_INDEX = 1;
- protected static byte[] decrypt(byte[] src) {
- try {
- byte[] zipsrc = CODEC.decode(src);
- Inflater decompressor = new Inflater();
- byte[] uncompressed = new byte[zipsrc.length * 5];
- decompressor.setInput(zipsrc);
- int totalOut = decompressor.inflate(uncompressed);
- byte[] out = new byte[totalOut];
- System.arraycopy(uncompressed, 0, out, 0, totalOut);
- decompressor.end();
- return out;
- } catch (Exception e) {
- throw new FacesException("Error decode resource data", e);
- }
- }
+ //index of capturing group denoting version
+ private static final int DATA_SEPARATOR_DATA_GROUP_INDEX = 2;
- public static String encodeResourceData(String resourceName, Object storeData,
- String resourceVersion) {
-
- StringBuffer uri = new StringBuffer();//
ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
- uri.append(resourceName);
- // append serialized data as Base-64 encoded request string.
- if (storeData != null) {
- try {
- byte[] objectData;
- if (storeData instanceof byte[]) {
- objectData = (byte[]) storeData;
- uri.append(DATA_BYTES_SEPARATOR);
- } else {
- ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(
- 1024);
- ObjectOutputStream objStream = new ObjectOutputStream(
- dataSteram);
- objStream.writeObject(storeData);
- objStream.flush();
- objStream.close();
- dataSteram.close();
- objectData = dataSteram.toByteArray();
- uri.append(DATA_SEPARATOR);
- }
- byte[] dataArray = encrypt(objectData);
- uri.append(new String(dataArray, "ISO-8859-1"));
+ protected static byte[] encrypt(byte[] src) {
+ try {
+ Deflater compressor = new Deflater(Deflater.BEST_SPEED);
+ byte[] compressed = new byte[src.length + 100];
+ compressor.setInput(src);
+ compressor.finish();
+ int totalOut = compressor.deflate(compressed);
+ byte[] zipsrc = new byte[totalOut];
+ System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
+ compressor.end();
+ return CODEC.encode(zipsrc);
+ } catch (Exception e) {
+ throw new FacesException("Error encode resource data", e);
+ }
+ }
- // / byte[] objectData = dataSteram.toByteArray();
- // / uri.append("?").append(new
- // String(Base64.encodeBase64(objectData),
- // / "ISO-8859-1"));
- } catch (Exception e) {
- resourceLogger.error(Messages.getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
- }
- }
-
- if (resourceVersion != null && resourceVersion.length() != 0) {
- uri.append(VERSION_SEPARATOR);
- uri.append(resourceVersion);
- }
+ protected static byte[] decrypt(byte[] src) {
+ try {
+ byte[] zipsrc = CODEC.decode(src);
+ Inflater decompressor = new Inflater();
+ byte[] uncompressed = new byte[zipsrc.length * 5];
+ decompressor.setInput(zipsrc);
+ int totalOut = decompressor.inflate(uncompressed);
+ byte[] out = new byte[totalOut];
+ System.arraycopy(uncompressed, 0, out, 0, totalOut);
+ decompressor.end();
+ return out;
+ } catch (Exception e) {
+ throw new FacesException("Error decode resource data", e);
+ }
+ }
+
+ public static String encodeResourceData(String resourceName, Object storeData,
+ String resourceVersion) {
+
+ StringBuilder uri = new StringBuilder();//
ResourceServlet.DEFAULT_SERVLET_PATH).append("/");
+ uri.append(resourceName);
+ // append serialized data as Base-64 encoded request string.
+ if (storeData != null) {
+ try {
+ byte[] objectData;
+ if (storeData instanceof byte[]) {
+ objectData = (byte[]) storeData;
+ uri.append(DATA_BYTES_SEPARATOR);
+ } else {
+ ByteArrayOutputStream dataSteram = new ByteArrayOutputStream(1024);
+ ObjectOutputStream objStream = new ObjectOutputStream(dataSteram);
+ objStream.writeObject(storeData);
+ objStream.flush();
+ objStream.close();
+ dataSteram.close();
+ objectData = dataSteram.toByteArray();
+ uri.append(DATA_SEPARATOR);
+ }
+ byte[] dataArray = encrypt(objectData);
+ uri.append(new String(dataArray, "ISO-8859-1"));
+
+ // / byte[] objectData = dataSteram.toByteArray();
+ // / uri.append("?").append(new
+ // String(Base64.encodeBase64(objectData),
+ // / "ISO-8859-1"));
+ } catch (Exception e) {
+
RESOURCE_LOGGER.error(Messages.getMessage(Messages.QUERY_STRING_BUILDING_ERROR), e);
+ }
+ }
+
+ if (resourceVersion != null && resourceVersion.length() != 0) {
+ uri.append(VERSION_SEPARATOR);
+ uri.append(resourceVersion);
+ }
//boolean isGlobal = !resource.isSessionAware();
-
+
// String resourceURL = getFacesResourceURL(context,
// uri.toString(), false /*isGlobal*/);//
context.getApplication().getViewHandler().getResourceURL(context,uri.toString());
- //if (!isGlobal) {
- // resourceURL = context.getExternalContext().encodeResourceURL(
- // resourceURL);
- //}
+ //if (!isGlobal) {
+ // resourceURL = context.getExternalContext().encodeResourceURL(
+ // resourceURL);
+ //}
// if (log.isDebugEnabled()) {
// log.debug(Messages.getMessage(Messages.BUILD_RESOURCE_URI_INFO,
// resource.getKey(), resourceURL));
// }
- return uri.toString();// context.getExternalContext().encodeResourceURL(resourceURL);
+ return uri.toString();//
context.getExternalContext().encodeResourceURL(resourceURL);
}
-
+
public static String getResourceName(String resourceUri) {
- String resourceName = resourceUri;
- Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(resourceName);
- if (matcher.find()) {
- int data = matcher.start();
- resourceName = resourceName.substring(0, data);
- } else {
- int idx = resourceName.indexOf(VERSION_SEPARATOR);
- if (idx > 0) {
- resourceName = resourceName.substring(0, idx);
- }
- }
+ String resourceName = resourceUri;
+ Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(resourceName);
+ if (matcher.find()) {
+ int data = matcher.start();
+ resourceName = resourceName.substring(0, data);
+ } else {
+ int idx = resourceName.indexOf(VERSION_SEPARATOR);
+ if (idx > 0) {
+ resourceName = resourceName.substring(0, idx);
+ }
+ }
- return resourceName;
+ return resourceName;
}
-
+
public static String getResourceVersion(String resourceUri) {
- int idx = resourceUri.indexOf(VERSION_SEPARATOR);
- if (idx > 0) {
- return resourceUri.substring(idx + VERSION_SEPARATOR.length());
- }
-
- return null;
+ int idx = resourceUri.indexOf(VERSION_SEPARATOR);
+ if (idx > 0) {
+ return resourceUri.substring(idx + VERSION_SEPARATOR.length());
+ }
+
+ return null;
}
-
+
public static Object getResourceData(String resourceUri) {
- Object data = null;
- String dataString = null;
- Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(resourceUri);
- if (matcher.find()) {
- if (resourceLogger.isDebugEnabled()) {
- resourceLogger.debug(Messages.getMessage(
- Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, resourceUri,
- dataString));
- }
- dataString = matcher.group(DATA_SEPARATOR_DATA_GROUP_INDEX);
- byte[] objectArray = null;
- byte[] dataArray;
- try {
- dataArray = dataString.getBytes("ISO-8859-1");
- objectArray = decrypt(dataArray);
- } catch (UnsupportedEncodingException e1) {
- // default encoding always presented.
- }
- if ("B".equals(matcher.group(DATA_SEPARATOR_TYPE_GROUP_INDEX))) {
- data = objectArray;
- } else {
- try {
- ObjectInputStream in = new ObjectInputStream(
- new ByteArrayInputStream(objectArray));
- data = in.readObject();
- } catch (StreamCorruptedException e) {
- resourceLogger.error(Messages
- .getMessage(Messages.STREAM_CORRUPTED_ERROR), e);
- } catch (IOException e) {
- resourceLogger.error(Messages
- .getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR),
- e);
- } catch (ClassNotFoundException e) {
- resourceLogger.error(
- Messages
- .getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR),
- e);
- }
- }
- }
+ Object data = null;
+ Matcher matcher = DATA_SEPARATOR_PATTERN.matcher(resourceUri);
+ if (!matcher.find()) {
+ return data;
+ }
- return data;
+ if (RESOURCE_LOGGER.isDebugEnabled()) {
+ RESOURCE_LOGGER.debug(Messages.getMessage(
+ Messages.RESTORE_DATA_FROM_RESOURCE_URI_INFO, resourceUri, null));
+ }
+
+ String dataString = matcher.group(DATA_SEPARATOR_DATA_GROUP_INDEX);
+ byte[] objectArray = null;
+ try {
+ byte[] dataArray = dataString.getBytes("ISO-8859-1");
+ objectArray = decrypt(dataArray);
+ } catch (UnsupportedEncodingException e1) {
+ // default encoding always presented.
+ }
+
+
+ if ("B".equals(matcher.group(DATA_SEPARATOR_TYPE_GROUP_INDEX))) {
+ data = objectArray;
+ } else {
+ try {
+ ObjectInputStream in = new ObjectInputStream(
+ new ByteArrayInputStream(objectArray));
+ data = in.readObject();
+ } catch (StreamCorruptedException e) {
+
RESOURCE_LOGGER.error(Messages.getMessage(Messages.STREAM_CORRUPTED_ERROR), e);
+ } catch (IOException e) {
+
RESOURCE_LOGGER.error(Messages.getMessage(Messages.DESERIALIZE_DATA_INPUT_ERROR), e);
+ } catch (ClassNotFoundException e) {
+
RESOURCE_LOGGER.error(Messages.getMessage(Messages.DATA_CLASS_NOT_FOUND_ERROR), e);
+ }
+ }
+
+ return data;
}
-
+
public static String encodeResourceURL(FacesContext context, String url) {
- String mapping = Util.getMappingForRequest(context);
+ String mapping = Util.getMappingForRequest(context);
- String resourcePath = url;
- if (mapping.startsWith("/")) {
- if (mapping.length() != 1) {
- resourcePath = mapping + url;
- }
- } else {
- resourcePath += mapping;
- }
+ String resourcePath = url;
+ if (mapping.startsWith("/")) {
+ if (mapping.length() != 1) {
+ resourcePath = mapping + url;
+ }
+ } else {
+ resourcePath += mapping;
+ }
- ViewHandler viewHandler = context.getApplication().getViewHandler();
- return viewHandler.getResourceURL(context, resourcePath);
+ ViewHandler viewHandler = context.getApplication().getViewHandler();
+ return viewHandler.getResourceURL(context, resourcePath);
}
-
+
public static String decodeResourceURL(FacesContext context) {
- ExternalContext externalContext = context.getExternalContext();
- String resourceName = null;
+ ExternalContext externalContext = context.getExternalContext();
+ String resourceName = null;
- String facesMapping = Util.getMappingForRequest(context);
- if (facesMapping != null) {
- if (facesMapping.startsWith("/")) {
- //prefix mapping
- resourceName = externalContext.getRequestPathInfo();
- } else {
- String requestServletPath = externalContext.getRequestServletPath();
- resourceName = requestServletPath.substring(0,
- requestServletPath.length() - facesMapping.length());
- }
- }
-
- return resourceName;
+ String facesMapping = Util.getMappingForRequest(context);
+ if (facesMapping != null) {
+ if (facesMapping.startsWith("/")) {
+ //prefix mapping
+ resourceName = externalContext.getRequestPathInfo();
+ } else {
+ String requestServletPath = externalContext.getRequestServletPath();
+ resourceName = requestServletPath.substring(0,
+ requestServletPath.length() - facesMapping.length());
+ }
+ }
+
+ return resourceName;
}
-
+
public static void copyStreamContent(InputStream is, OutputStream os) throws
IOException {
- ReadableByteChannel inChannel = Channels.newChannel(is);
- WritableByteChannel outChannel = Channels.newChannel(os);
-
- //TODO make this configurable
- ByteBuffer buffer = ByteBuffer.allocate(8192);
- int read;
-
- while ((read = inChannel.read(buffer)) > 0) {
- buffer.rewind();
- buffer.limit(read);
-
- while (read > 0) {
- read -= outChannel.write(buffer);
- }
-
- buffer.clear();
- }
+ ReadableByteChannel inChannel = Channels.newChannel(is);
+ WritableByteChannel outChannel = Channels.newChannel(os);
+
+ //TODO make this configurable
+ ByteBuffer buffer = ByteBuffer.allocate(8192);
+ int read;
+
+ while ((read = inChannel.read(buffer)) > 0) {
+ buffer.rewind();
+ buffer.limit(read);
+
+ while (read > 0) {
+ read -= outChannel.write(buffer);
+ }
+
+ buffer.clear();
+ }
}
}
Modified: root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java
===================================================================
---
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/test/java/org/ajax4jsf/cache/LRUMapCacheTest.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -25,7 +25,9 @@
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;
-import org.ajax4jsf.cache.LRUMapCache.CacheMap;
+import org.ajax4jsf.cache.lru.CacheMap;
+import org.ajax4jsf.cache.lru.LRUMapCache;
+import org.ajax4jsf.cache.lru.CacheEntry;
import org.junit.Assert;
import org.junit.Test;
@@ -76,23 +78,23 @@
@Test
public void testCacheMap() throws Exception {
- CacheMap cacheMap = new LRUMapCache.CacheMap();
- Assert.assertTrue(cacheMap.expirationQueue.isEmpty());
+ CacheMap cacheMap = new CacheMap();
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
- LRUMapCache.CacheEntry cacheEntry = new LRUMapCache.CacheEntry("key",
"value", new Date(System.currentTimeMillis() + 1000));
+ 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.expirationQueue.isEmpty());
+ Assert.assertFalse(cacheMap.getExpirationQueue().isEmpty());
cacheMap.clear();
- Assert.assertTrue(cacheMap.expirationQueue.isEmpty());
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
- cacheMap.put("key2", new LRUMapCache.CacheEntry("key2",
"value2", new Date(System.currentTimeMillis() + 1000)));
+ cacheMap.put("key2", new CacheEntry("key2", "value2", new
Date(System.currentTimeMillis() + 1000)));
Assert.assertNotNull(cacheMap.get("key2"));
cacheMap.remove("key2");
- Assert.assertTrue(cacheMap.expirationQueue.isEmpty());
+ Assert.assertTrue(cacheMap.getExpirationQueue().isEmpty());
}
@Test
Modified:
root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java
===================================================================
---
root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/test/java/org/richfaces/resource/AbstractCacheableResourceTest.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -44,9 +44,6 @@
*/
public class AbstractCacheableResourceTest extends AbstractFacesTest {
- /**
- *
- */
private static final int MILLISECONDS_IN_HOUR = 60 * 60 * 1000;
/* HTTP Date format required by the HTTP/1.1 RFC */
@@ -78,67 +75,67 @@
public void testInitialRequest() throws Exception {
MockAbstractResource defaultResource = new MockAbstractResource();
- assertNull(defaultResource.matchesEntityTag(facesContext));
- assertNull(defaultResource.matchesLastModified(facesContext));
+ assertNull(defaultResource.isMatchesEntityTag(facesContext));
+ assertNull(defaultResource.isMatchesLastModified(facesContext));
MockAbstractResource entityTaggedResource = new MockAbstractResource();
entityTaggedResource.setEntityTag("3456");
- assertNull(entityTaggedResource.matchesEntityTag(facesContext));
- assertNull(entityTaggedResource.matchesLastModified(facesContext));
+ assertNull(entityTaggedResource.isMatchesEntityTag(facesContext));
+ assertNull(entityTaggedResource.isMatchesLastModified(facesContext));
MockAbstractResource timeKnownResource = new MockAbstractResource();
timeKnownResource.setLastModified(new Date(System.currentTimeMillis() -
MILLISECONDS_IN_HOUR));
- assertNull(timeKnownResource.matchesEntityTag(facesContext));
- assertNull(timeKnownResource.matchesLastModified(facesContext));
+ assertNull(timeKnownResource.isMatchesEntityTag(facesContext));
+ assertNull(timeKnownResource.isMatchesLastModified(facesContext));
}
public void testEntityTag() throws Exception {
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
"\"3456\""));
MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.matchesEntityTag(facesContext));
+ assertFalse(defaultResource.isMatchesEntityTag(facesContext));
MockAbstractResource entityTaggedResource = new MockAbstractResource();
entityTaggedResource.setEntityTag("\"3456\"");
- assertEquals(Boolean.TRUE, entityTaggedResource.matchesEntityTag(facesContext));
+ assertTrue(entityTaggedResource.isMatchesEntityTag(facesContext));
MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
unmatchedTaggedResource.setEntityTag("\"123\"");
- assertEquals(Boolean.FALSE, unmatchedTaggedResource.matchesEntityTag(facesContext));
+ assertFalse(unmatchedTaggedResource.isMatchesEntityTag(facesContext));
}
public void testWeakEntityTag() throws Exception {
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
"W/\"3456\""));
MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.FALSE, defaultResource.isMatchesEntityTag(facesContext));
MockAbstractResource entityTaggedResource = new MockAbstractResource();
entityTaggedResource.setEntityTag("\"3456\"");
- assertEquals(Boolean.TRUE, entityTaggedResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.TRUE, entityTaggedResource.isMatchesEntityTag(facesContext));
MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
unmatchedTaggedResource.setEntityTag("\"123\"");
- assertEquals(Boolean.FALSE, unmatchedTaggedResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.FALSE, unmatchedTaggedResource.isMatchesEntityTag(facesContext));
}
public void testMultiEntityTags() throws Exception {
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
"W/\"3456\", \"012\""));
MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.FALSE, defaultResource.isMatchesEntityTag(facesContext));
MockAbstractResource entityTaggedResource = new MockAbstractResource();
entityTaggedResource.setEntityTag("\"3456\"");
- assertEquals(Boolean.TRUE, entityTaggedResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.TRUE, entityTaggedResource.isMatchesEntityTag(facesContext));
MockAbstractResource anotherTaggedResource = new MockAbstractResource();
anotherTaggedResource.setEntityTag("W/\"012\"");
- assertEquals(Boolean.TRUE, anotherTaggedResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.TRUE, anotherTaggedResource.isMatchesEntityTag(facesContext));
MockAbstractResource unmatchedTaggedResource = new MockAbstractResource();
unmatchedTaggedResource.setEntityTag("\"123\"");
- assertEquals(Boolean.FALSE, unmatchedTaggedResource.matchesEntityTag(facesContext));
+ assertEquals(Boolean.FALSE, unmatchedTaggedResource.isMatchesEntityTag(facesContext));
}
public void testIfModified() throws Exception {
@@ -149,15 +146,15 @@
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
RFC1123_DATE_FORMATTER.format(baseDate)));
MockAbstractResource defaultResource = new MockAbstractResource();
- assertEquals(Boolean.FALSE, defaultResource.matchesLastModified(facesContext));
+ assertEquals(Boolean.FALSE, defaultResource.isMatchesLastModified(facesContext));
MockAbstractResource actualResource = new MockAbstractResource();
actualResource.setLastModified(beforeBaseDate);
- assertEquals(Boolean.TRUE, actualResource.matchesLastModified(facesContext));
+ assertEquals(Boolean.TRUE, actualResource.isMatchesLastModified(facesContext));
MockAbstractResource expiredResource = new MockAbstractResource();
expiredResource.setLastModified(afterBaseDate);
- assertEquals(Boolean.FALSE, expiredResource.matchesLastModified(facesContext));
+ assertEquals(Boolean.FALSE, expiredResource.isMatchesLastModified(facesContext));
}
private static class BooleanAnswer implements IAnswer<Boolean> {
@@ -170,7 +167,7 @@
public void setValue(Boolean value) {
this.value = value;
}
- };
+ }
private static abstract class AbstractTestResource extends AbstractCacheableResource {
@Override
@@ -184,65 +181,82 @@
}
@Override
- protected Boolean matchesEntityTag(FacesContext context) {
- return super.matchesEntityTag(context);
+ protected boolean isMatchesEntityTag(FacesContext context, String matchHeaderValue) {
+ return super.isMatchesEntityTag(context, matchHeaderValue);
}
-
- @Override
- protected Boolean matchesLastModified(FacesContext context) {
- return super.matchesLastModified(context);
- }
- }
-
- public void testUserAgentNeedsUpdate() throws Exception {
- BooleanAnswer tagMatches = new BooleanAnswer();
- BooleanAnswer lastModifiedMatches = new BooleanAnswer();
- BooleanAnswer cacheable = new BooleanAnswer();
-
- AbstractCacheableResource resource =
EasyMock.createNiceMock(AbstractTestResource.class,
- AbstractTestResource.class.getDeclaredMethods());
- EasyMock.expect(resource.isCacheable(facesContext)).andStubAnswer(cacheable);
- EasyMock.expect(resource.matchesEntityTag(facesContext)).andStubAnswer(tagMatches);
- EasyMock.expect(resource.matchesLastModified(facesContext)).andStubAnswer(lastModifiedMatches);
-
- EasyMock.replay(resource);
-
- cacheable.setValue(false);
- assertTrue(resource.userAgentNeedsUpdate(facesContext));
- cacheable.setValue(true);
-
- tagMatches.setValue(Boolean.FALSE);
- lastModifiedMatches.setValue(Boolean.TRUE);
- assertTrue(resource.userAgentNeedsUpdate(facesContext));
+ @Override
+ protected boolean isMatchesLastModified(FacesContext context, String
modifiedCondition) {
+ return super.isMatchesLastModified(context, modifiedCondition);
+ }
+ }
- tagMatches.setValue(Boolean.TRUE);
- lastModifiedMatches.setValue(Boolean.FALSE);
- assertTrue(resource.userAgentNeedsUpdate(facesContext));
+ public void testUserAgentNeedsUpdate() throws Exception {
+ BooleanAnswer tagMatches = new BooleanAnswer();
+ BooleanAnswer lastModifiedMatches = new BooleanAnswer();
+ BooleanAnswer cacheable = new BooleanAnswer();
- tagMatches.setValue(null);
- lastModifiedMatches.setValue(Boolean.FALSE);
- assertTrue(resource.userAgentNeedsUpdate(facesContext));
+ AbstractCacheableResource resource =
EasyMock.createNiceMock(AbstractTestResource.class,
+ AbstractTestResource.class.getDeclaredMethods());
- tagMatches.setValue(Boolean.FALSE);
- lastModifiedMatches.setValue(null);
- assertTrue(resource.userAgentNeedsUpdate(facesContext));
+ EasyMock.expect(resource.isCacheable(facesContext)).andStubAnswer(cacheable);
- tagMatches.setValue(Boolean.TRUE);
- lastModifiedMatches.setValue(null);
- assertFalse(resource.userAgentNeedsUpdate(facesContext));
+ String matchHeaderValue = RFC1123_DATE_FORMATTER.format(new Date());
+
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
matchHeaderValue));
+ EasyMock.expect(resource.isMatchesEntityTag(facesContext,
matchHeaderValue)).andStubAnswer(tagMatches);
- tagMatches.setValue(null);
- lastModifiedMatches.setValue(Boolean.TRUE);
- assertFalse(resource.userAgentNeedsUpdate(facesContext));
+ String modifiedCondition = "\"1234\"";
+
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
modifiedCondition));
+ EasyMock.expect(resource.isMatchesLastModified(facesContext,
modifiedCondition)).andStubAnswer(lastModifiedMatches);
- tagMatches.setValue(Boolean.TRUE);
- lastModifiedMatches.setValue(Boolean.TRUE);
- assertFalse(resource.userAgentNeedsUpdate(facesContext));
+ EasyMock.replay(resource);
- cacheable.setValue(false);
- assertTrue(resource.userAgentNeedsUpdate(facesContext));
- }
+ cacheable.setValue(false);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+
+ cacheable.setValue(true);
+
+ tagMatches.setValue(Boolean.TRUE);
+ lastModifiedMatches.setValue(Boolean.TRUE);
+ assertFalse(resource.userAgentNeedsUpdate(facesContext));
+
+ tagMatches.setValue(Boolean.FALSE);
+ lastModifiedMatches.setValue(Boolean.FALSE);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+ tagMatches.setValue(Boolean.FALSE);
+ lastModifiedMatches.setValue(Boolean.TRUE);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+ tagMatches.setValue(Boolean.TRUE);
+ lastModifiedMatches.setValue(Boolean.FALSE);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+
+
+
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
(String) null));
+ lastModifiedMatches.setValue(Boolean.FALSE);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+ lastModifiedMatches.setValue(Boolean.TRUE);
+ assertFalse(resource.userAgentNeedsUpdate(facesContext));
+
+
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
matchHeaderValue));
+
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
(String) null));
+ tagMatches.setValue(Boolean.FALSE);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+ tagMatches.setValue(Boolean.TRUE);
+ assertFalse(resource.userAgentNeedsUpdate(facesContext));
+
+
this.connection.addRequestHeaders(Collections.singletonMap("If-Modified-Since",
(String) null));
+
this.connection.addRequestHeaders(Collections.singletonMap("If-None-Match",
(String) null));
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+
+ cacheable.setValue(false);
+ assertTrue(resource.userAgentNeedsUpdate(facesContext));
+ }
}
Modified:
root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java
===================================================================
---
root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java 2009-10-21
19:40:42 UTC (rev 15744)
+++
root/framework/trunk/impl/src/test/java/org/richfaces/resource/ResourceUtilsTest.java 2009-10-22
07:22:02 UTC (rev 15745)
@@ -76,7 +76,7 @@
ResourceUtils.matchTag(null, "W/\"123-4567890\",
\"123-4567891\"");
fail();
- } catch (NullPointerException e) {
+ } catch (IllegalArgumentException e) {
//ok
}
@@ -84,7 +84,7 @@
ResourceUtils.matchTag("W/\"123-4567890\"", null);
fail();
- } catch (NullPointerException e) {
+ } catch (IllegalArgumentException e) {
//ok
}