Permalink
Browse files

Reverted the changes accidentally pulled in from the master branch.

  • Loading branch information...
1 parent 629fdda commit d2edbbd9250516449b7ac0fb001ada719ab20963 @pledbrook pledbrook committed Nov 17, 2010
Showing with 914 additions and 958 deletions.
  1. +1 −1 .classpath
  2. +2 −2 Grails.iml
  3. +1 −1 bin/startGrails
  4. +2 −2 bin/startGrails.bat
  5. +1 −1 build.gradle
  6. +2 −2 build.properties
  7. +0 −5 dependencies.txt
  8. +1 −2 ivy.xml
  9. BIN lib/h2-1.2.144.jar
  10. +2 −2 scripts/SchemaExport.groovy
  11. +4 −4 src/grails/grails-app/conf/DataSource.groovy
  12. +2 −2 src/java/grails/spring/BeanBuilder.java
  13. +3 −3 src/java/grails/util/AbstractBuildSettings.java
  14. +2 −1 src/java/org/codehaus/groovy/grails/cli/GrailsScriptRunner.java
  15. +1 −1 src/java/org/codehaus/groovy/grails/commons/DefaultGrailsControllerClass.java
  16. +302 −293 src/java/org/codehaus/groovy/grails/orm/hibernate/support/ClosureEventListener.java
  17. +86 −87 src/java/org/codehaus/groovy/grails/orm/hibernate/support/ClosureEventTriggeringInterceptor.java
  18. +1 −3 ...java/org/codehaus/groovy/grails/orm/hibernate/support/HibernatePersistenceContextInterceptor.java
  19. +16 −23 src/java/org/codehaus/groovy/grails/orm/hibernate/support/SoftKey.java
  20. +9 −8 src/java/org/codehaus/groovy/grails/plugins/codecs/HTMLCodec.java
  21. +15 −46 src/java/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPlugin.groovy
  22. +2 −3 src/java/org/codehaus/groovy/grails/plugins/web/ControllersGrailsPlugin.groovy
  23. +1 −2 src/java/org/codehaus/groovy/grails/resolve/IvyDependencyManager.groovy
  24. +11 −10 src/java/org/codehaus/groovy/grails/support/ResourceAwareTemplateEngine.java
  25. +5 −5 src/java/org/codehaus/groovy/grails/web/context/GrailsConfigUtils.java
  26. +51 −49 src/java/org/codehaus/groovy/grails/web/mapping/DefaultUrlMappingsHolder.java
  27. +118 −133 src/java/org/codehaus/groovy/grails/web/mapping/UrlCreatorCache.java
  28. +15 −13 src/java/org/codehaus/groovy/grails/web/mapping/UrlMappingsHolderFactoryBean.java
  29. +3 −0 src/java/org/codehaus/groovy/grails/web/pages/GSPResponseWriter.java
  30. +51 −50 src/java/org/codehaus/groovy/grails/web/pages/GroovyPageMetaInfo.java
  31. +70 −63 src/java/org/codehaus/groovy/grails/web/pages/GroovyPagesTemplateEngine.java
  32. +1 −1 src/java/org/codehaus/groovy/grails/web/servlet/mvc/CommandObjectEnablingPostProcessor.java
  33. +1 −0 src/java/org/codehaus/groovy/grails/web/servlet/mvc/SimpleGrailsControllerHelper.java
  34. +1 −1 src/java/org/codehaus/groovy/grails/web/taglib/GroovyConditionalTag.java
  35. +0 −9 src/java/org/codehaus/groovy/grails/web/util/CodecPrintWriter.java
  36. +2 −1 src/java/org/codehaus/groovy/grails/web/util/GrailsPrintWriter.java
  37. +59 −59 src/java/org/codehaus/groovy/grails/web/util/StreamCharBuffer.java
  38. +2 −2 src/test/grails/spring/resources1.groovy
  39. +1 −1 src/test/grails/util/GrailsUtilTests.java
  40. +2 −2 src/test/org/codehaus/groovy/grails/cli/support/JndiBindingSupportTests.groovy
  41. +2 −2 src/test/org/codehaus/groovy/grails/commons/GrailsPluginManagerTests.groovy
  42. +1 −1 src/test/org/codehaus/groovy/grails/commons/spring/GrailsRuntimeConfiguratorTests.java
  43. +2 −2 src/test/org/codehaus/groovy/grails/orm/hibernate/AbstractGrailsHibernateTests.groovy
  44. +1 −1 src/test/org/codehaus/groovy/grails/orm/hibernate/ListMethodTests.groovy
  45. +2 −2 src/test/org/codehaus/groovy/grails/orm/hibernate/MappingDslTests.groovy
  46. +6 −6 src/test/org/codehaus/groovy/grails/orm/hibernate/cfg/GORMNamespaceHandlerTests.groovy
  47. +3 −3 src/test/org/codehaus/groovy/grails/orm/hibernate/grails-hibernate-configuration-tests.xml
  48. +2 −2 src/test/org/codehaus/groovy/grails/orm/support/TransactionManagerPostProcessorTests.groovy
  49. +1 −1 src/test/org/codehaus/groovy/grails/plugins/CoreGrailsPluginTests.groovy
  50. +21 −21 src/test/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPluginTests.groovy
  51. +2 −2 src/test/org/codehaus/groovy/grails/plugins/grails-app/conf/NonPooledApplicationDataSource.groovy
  52. +2 −2 src/test/org/codehaus/groovy/grails/plugins/grails-app/conf/PooledApplicationDataSource.groovy
  53. +1 −1 src/test/org/codehaus/groovy/grails/plugins/scaffolding/ScaffoldingGrailsPluginTests.groovy
  54. +1 −1 src/test/org/codehaus/groovy/grails/plugins/services/ServicesGrailsPluginTests.groovy
  55. +2 −2 src/test/org/codehaus/groovy/grails/reload/TransactionalServiceReloadTests.groovy
  56. +6 −6 src/test/org/codehaus/groovy/grails/resolve/IvyDependencyManagerTests.groovy
  57. +2 −2 src/test/org/codehaus/groovy/grails/scaffolding/grails-scaffolding-tests.xml
  58. +4 −4 src/test/org/codehaus/groovy/grails/web/taglib/FormTagLib2Tests.groovy
  59. +4 −4 test/test-projects/plugin-build-settings/grails-app/conf/DataSource.groovy
View
2 .classpath
@@ -24,6 +24,7 @@
<classpathentry kind="lib" path="lib/dom4j-1.6.1.jar"/>
<classpathentry kind="lib" path="lib/ejb3-persistence-1.0.2.GA.jar"/>
<classpathentry kind="lib" path="lib/gant_groovy1.7-1.9.2.jar"/>
+ <classpathentry kind="lib" path="lib/hsqldb-1.8.0.10.jar"/>
<classpathentry kind="lib" path="lib/jcl-over-slf4j-1.5.8.jar"/>
<classpathentry kind="lib" path="lib/jsp-api-2.0.jar"/>
<classpathentry kind="lib" path="lib/jstl-1.1.2.jar"/>
@@ -78,6 +79,5 @@
<classpathentry kind="lib" path="lib/org.springframework.webflow-2.0.8.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/groovy-all-1.7.5.jar"/>
<classpathentry kind="lib" path="lib/concurrentlinkedhashmap-lru-1.0_jdk5.jar"/>
- <classpathentry kind="lib" path="lib/h2-1.2.144.jar"/>
<classpathentry kind="output" path="target/eclipse/bin-output"/>
</classpath>
View
4 Grails.iml
@@ -94,9 +94,9 @@
<orderEntry type="library" exported="" name="Ivy" level="project" />
<orderEntry type="library" exported="" name="JUnit" level="project" />
<orderEntry type="module-library" exported="">
- <library name="H2">
+ <library name="HSQLDB">
<CLASSES>
- <root url="jar://$MODULE_DIR$/lib/h2-1.2.144.jar!/" />
+ <root url="jar://$MODULE_DIR$/lib/hsqldb-1.8.0.10.jar!/" />
</CLASSES>
<JAVADOC />
<SOURCES />
View
2 bin/startGrails
@@ -114,7 +114,7 @@ fi
if [ -z "$GROOVY_CONF" ]; then
GROOVY_CONF="$GRAILS_HOME/conf/groovy-starter.conf"
fi
-STARTER_CLASSPATH="$GRAILS_HOME/lib/groovy-all-1.7.5.jar:$GRAILS_HOME/dist/grails-bootstrap-1.4.0.BUILD-SNAPSHOT.jar"
+STARTER_CLASSPATH="$GRAILS_HOME/lib/groovy-all-1.7.5.jar:$GRAILS_HOME/dist/grails-bootstrap-1.3.6.BUILD-SNAPSHOT.jar"
# Allow access to Cocoa classes on OS X
if $darwin; then
View
4 bin/startGrails.bat
@@ -106,7 +106,7 @@ set CMD_LINE_ARGS=%$
:execute
@rem Setup the command line
-set STARTER_CLASSPATH=%GRAILS_HOME%\lib\groovy-all-1.7.5.jar;%GRAILS_HOME%\dist\grails-bootstrap-1.4.0.BUILD-SNAPSHOT.jar
+set STARTER_CLASSPATH=%GRAILS_HOME%\lib\groovy-all-1.7.5.jar;%GRAILS_HOME%\dist\grails-bootstrap-1.3.6.BUILD-SNAPSHOT.jar
if exist "%USERPROFILE%/.groovy/init.bat" call "%USERPROFILE%/.groovy/init.bat"
@@ -127,7 +127,7 @@ set TOOLS_JAR=%JAVA_HOME%\lib\tools.jar
if "%JAVA_OPTS%" == "" set JAVA_OPTS=-Xmx512m -XX:MaxPermSize=96m
set JAVA_OPTS=%JAVA_OPTS% -Dprogram.name="%PROGNAME%"
set JAVA_OPTS=%JAVA_OPTS% -Dgrails.home="%GRAILS_HOME%"
-set JAVA_OPTS=%JAVA_OPTS% -Dgrails.version="1.4.0.BUILD-SNAPSHOT"
+set JAVA_OPTS=%JAVA_OPTS% -Dgrails.version="1.3.6.BUILD-SNAPSHOT"
set JAVA_OPTS=%JAVA_OPTS% -Dbase.dir="."
set JAVA_OPTS=%JAVA_OPTS% -Dtools.jar="%TOOLS_JAR%"
set JAVA_OPTS=%JAVA_OPTS% -Dgroovy.starter.conf="%STARTER_CONF%"
View
2 build.gradle
@@ -9,7 +9,7 @@ buildscript {
apply id: 'groovy'
-version = '1.4.0.BUILD-SNAPSHOT'
+version = '1.3.6.BUILD-SNAPSHOT'
sourceCompatibility = "1.5"
targetCompatibility = "1.5"
View
4 build.properties
@@ -1,5 +1,5 @@
-grails.version=1.4.0.BUILD-SNAPSHOT
-bundlor.grails.version=1.4.0.BUILD-SNAPSHOT
+grails.version=1.3.6.BUILD-SNAPSHOT
+bundlor.grails.version=1.3.6.BUILD-SNAPSHOT
grails.src.commons=src/commons
grails.src.groovy=src/groovy
View
5 dependencies.txt
@@ -108,11 +108,6 @@ The following libraries are included in Grails because they are required either
- required for building Grails core
- required for running Grails applications (With an in-memory database)
-* h2-1.2.144.jar
-- H2 1.2.144 (http://www.h2database.com/) H2 License (see http://www.h2database.com/html/license.html)
-- required for building Grails core
-- required for running Grails applications (With an in-memory database)
-
* javassist-3.8.0.GA.jar
- Javassist 3.8 (http://www.jboss.org/javassist/) MPL or LGPL License
- required for running Grails applications
View
3 ivy.xml
@@ -27,8 +27,7 @@
<dependency org="jakarta" name="oro" rev="2.0.8"/>
<dependency org="org.springframework" name="spring" rev="2.0"/>
<dependency org="cglib" name="cglib-nodep" rev="2.1_3"/>
- <dependency org="hsqldb" name="hsqldb" rev="1.8.0.5"/>
- <dependency org="com.h2database" name="h2" rev="1.2.144"/>
+ <dependency org="hsqldb" name="hsqldb" rev="1.8.0.5"/>
<dependency org="oscache" name="oscache" rev="2.4.1"/>
<!--<dependency org="asm" name="asm" rev="1.3.4"/>
<dependency org="asm" name="asm-util" rev="1.3.4"/>-->
View
BIN lib/h2-1.2.144.jar
Binary file not shown.
View
4 scripts/SchemaExport.groovy
@@ -65,9 +65,9 @@ def populateProperties = {
props.'hibernate.connection.username' = dsConfig?.dataSource?.username ?: 'sa'
props.'hibernate.connection.password' = dsConfig?.dataSource?.password ?: ''
- props.'hibernate.connection.url' = dsConfig?.dataSource?.url ?: 'jdbc:h2:mem:testDB'
+ props.'hibernate.connection.url' = dsConfig?.dataSource?.url ?: 'jdbc:hsqldb:mem:testDB'
props.'hibernate.connection.driver_class' =
- dsConfig?.dataSource?.driverClassName ?: 'org.h2.Driver'
+ dsConfig?.dataSource?.driverClassName ?: 'org.hsqldb.jdbcDriver'
if (dsConfig?.dataSource?.configClass) {
if (dsConfig.dataSource.configClass instanceof Class) {
View
8 src/grails/grails-app/conf/DataSource.groovy
@@ -1,6 +1,6 @@
dataSource {
pooled = true
- driverClassName = "org.h2.Driver"
+ driverClassName = "org.hsqldb.jdbcDriver"
username = "sa"
password = ""
}
@@ -14,19 +14,19 @@ environments {
development {
dataSource {
dbCreate = "create-drop" // one of 'create', 'create-drop','update'
- url = "jdbc:h2:mem:devDB"
+ url = "jdbc:hsqldb:mem:devDB"
}
}
test {
dataSource {
dbCreate = "update"
- url = "jdbc:h2:mem:testDb"
+ url = "jdbc:hsqldb:mem:testDb"
}
}
production {
dataSource {
dbCreate = "update"
- url = "jdbc:h2:prodDb"
+ url = "jdbc:hsqldb:file:prodDb;shutdown=true"
}
}
}
View
4 src/java/grails/spring/BeanBuilder.java
@@ -55,8 +55,8 @@
* BeanBuilder builder = new BeanBuilder()
* builder.beans {
* dataSource(BasicDataSource) { // <--- invokeMethod
- * driverClassName = "org.h2.Driver"
- * url = "jdbc:h2:mem:grailsDB"
+ * driverClassName = "org.hsqldb.jdbcDriver"
+ * url = "jdbc:hsqldb:mem:grailsDB"
* username = "sa" // <-- setProperty
* password = ""
* settings = [mynew:"setting"]
View
6 src/java/grails/util/AbstractBuildSettings.java
@@ -15,11 +15,11 @@
import java.util.concurrent.ConcurrentLinkedQueue;
/**
- * Methods optimized to Java for the BuildSettings class.
+ * Methods optimized to Java for the BuildSettings class
*
* @since 1.3.4
*/
-public abstract class AbstractBuildSettings {
+abstract public class AbstractBuildSettings {
private static final String KEY_PLUGIN_DIRECTORY_RESOURCES = "pluginDirectoryResources";
private static final String KEY_INLINE_PLUGIN_LOCATIONS = "inlinePluginLocations";
@@ -123,7 +123,7 @@ public void addPluginDirectory(File location, boolean isInline) {
* @see getInlinePluginsFromConfiguration(Map, File)
*/
@SuppressWarnings({ "rawtypes" })
- protected Collection<File> getInlinePluginsFromConfiguration(@SuppressWarnings("hiding") Map config) {
+ protected Collection<File> getInlinePluginsFromConfiguration(Map config) {
return getInlinePluginsFromConfiguration(config, getBaseDir());
}
View
3 src/java/org/codehaus/groovy/grails/cli/GrailsScriptRunner.java
@@ -21,6 +21,7 @@
import grails.util.CosineSimilarity;
import grails.util.Environment;
import grails.util.GrailsNameUtils;
+import groovy.lang.Binding;
import groovy.lang.Closure;
import groovy.lang.ExpandoMetaClass;
import groovy.util.AntBuilder;
@@ -544,7 +545,7 @@ private int callPluginOrGrailsScript(String scriptName, String env) {
if (enteredValue == null) return 1;
int number = Integer.parseInt(enteredValue);
- File scriptFile = potentialScripts.get(number - 1);
+ File scriptFile = (File) potentialScripts.get(number - 1);
out.println("Running script "+ scriptFile.getAbsolutePath());
// We can now safely set the default environment
String scriptFileName = getScriptNameFromFile(scriptFile);
View
2 src/java/org/codehaus/groovy/grails/commons/DefaultGrailsControllerClass.java
@@ -225,7 +225,7 @@ public boolean isHttpMethodAllowedForAction(GroovyObject controller, final Strin
if (value instanceof List) {
List listOfMethods = (List)value;
isAllowed = CollectionUtils.exists(listOfMethods, new Predicate() {
- public boolean evaluate(@SuppressWarnings("hiding") Object value) {
+ public boolean evaluate(Object value) {
return httpMethod.equalsIgnoreCase(value.toString());
}
});
View
595 src/java/org/codehaus/groovy/grails/orm/hibernate/support/ClosureEventListener.java
@@ -72,298 +72,307 @@
* @author Lari Hotari
* @since 1.3.5
*/
-@SuppressWarnings({"rawtypes", "unchecked"})
public class ClosureEventListener implements SaveOrUpdateEventListener, PreLoadEventListener, PostLoadEventListener,
- PostInsertEventListener, PostUpdateEventListener, PostDeleteEventListener, PreDeleteEventListener,
- PreUpdateEventListener {
- private static final long serialVersionUID = 1L;
- private static final Log log = LogFactory.getLog(ClosureEventListener.class);
- private static final Object[] EMPTY_OBJECT_ARRAY = new Object[] {};
-
- EventTriggerCaller saveOrUpdateCaller;
- EventTriggerCaller beforeInsertCaller;
- EventTriggerCaller preLoadEventCaller;
- EventTriggerCaller postLoadEventListener;
- EventTriggerCaller postInsertEventListener;
- EventTriggerCaller postUpdateEventListener;
- EventTriggerCaller postDeleteEventListener;
- EventTriggerCaller preDeleteEventListener;
- EventTriggerCaller preUpdateEventListener;
- boolean shouldTimestamp = false;
- MetaProperty dateCreatedProperty;
- MetaProperty lastUpdatedProperty;
- MetaClass domainMetaClass;
- boolean failOnErrorEnabled = false;
- MetaProperty errorsProperty;
- Map validateParams;
- MetaMethod validateMethod;
-
- public ClosureEventListener(Class<?> domainClazz, boolean failOnError, List failOnErrorPackages) {
- initialize(domainClazz, failOnError, failOnErrorPackages);
- }
-
- private void initialize(Class<?> domainClazz, boolean failOnError, List failOnErrorPackages) {
- domainMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(domainClazz);
- dateCreatedProperty = domainMetaClass.getMetaProperty(GrailsDomainClassProperty.DATE_CREATED);
- lastUpdatedProperty = domainMetaClass.getMetaProperty(GrailsDomainClassProperty.LAST_UPDATED);
- if (dateCreatedProperty != null || lastUpdatedProperty != null) {
- Mapping m = GrailsDomainBinder.getMapping(domainClazz);
- shouldTimestamp = (m != null && !m.isAutoTimestamp()) ? false : true;
- }
-
- saveOrUpdateCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.ONLOAD_SAVE);
- beforeInsertCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_INSERT_EVENT);
- preLoadEventCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.ONLOAD_EVENT);
- if (preLoadEventCaller == null) {
- preLoadEventCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_LOAD_EVENT);
- }
- postLoadEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_LOAD_EVENT);
- postInsertEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_INSERT_EVENT);
- postUpdateEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_UPDATE_EVENT);
- postDeleteEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_DELETE_EVENT);
- preDeleteEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_DELETE_EVENT);
- preUpdateEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_UPDATE_EVENT);
-
- if (failOnErrorPackages.size() > 0) {
- failOnErrorEnabled = GrailsClassUtils.isClassBelowPackage(domainClazz, failOnErrorPackages);
- } else {
- failOnErrorEnabled = failOnError;
- }
-
- validateParams = new HashMap();
- validateParams.put(ValidatePersistentMethod.ARGUMENT_DEEP_VALIDATE, Boolean.FALSE);
-
- errorsProperty = domainMetaClass.getMetaProperty(AbstractDynamicPersistentMethod.ERRORS_PROPERTY);
-
- validateMethod = domainMetaClass.getMetaMethod(ValidatePersistentMethod.METHOD_SIGNATURE,
- new Object[] { Map.class });
- }
-
- private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
- Method method = ReflectionUtils.findMethod(domainClazz, event);
- if (method != null) {
- ReflectionUtils.makeAccessible(method);
- return new MethodCaller(method);
- }
-
- Field field = ReflectionUtils.findField(domainClazz, event);
- if (field != null) {
- ReflectionUtils.makeAccessible(field);
- return new FieldClosureCaller(field);
- }
-
- MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
- if (metaMethod != null) {
- return new MetaMethodCaller(metaMethod);
- }
-
- MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
- if (metaProperty != null) {
- return new MetaPropertyClosureCaller(metaProperty);
- }
-
- return null;
- }
-
- public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
- Object entity = event.getObject();
- boolean newEntity = !event.getSession().contains(entity);
- if (newEntity) {
- if (beforeInsertCaller != null) {
- beforeInsertCaller.call(entity);
- if (event.getSession().contains(entity)) {
- EntityEntry entry = event.getEntry();
- if (entry != null) {
- Object[] state = entry.getLoadedState();
- synchronizePersisterState(entity, entry.getPersister(), state);
- }
- }
- }
- if (shouldTimestamp) {
- long time = System.currentTimeMillis();
- if (dateCreatedProperty != null && newEntity) {
- Object now = DefaultGroovyMethods.newInstance(dateCreatedProperty.getType(), new Object[] { time });
- dateCreatedProperty.setProperty(entity, now);
- }
- if (lastUpdatedProperty != null) {
- Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] { time });
- lastUpdatedProperty.setProperty(entity, now);
- }
- }
- }
- }
-
- private void synchronizePersisterState(Object entity, EntityPersister persister, Object[] state) {
- String[] propertyNames = persister.getPropertyNames();
- for (int i = 0; i < propertyNames.length; i++) {
- String p = propertyNames[i];
- MetaProperty metaProperty = domainMetaClass.getMetaProperty(p);
- if (ClosureEventTriggeringInterceptor.IGNORED.contains(p) || metaProperty == null) {
- continue;
- }
- Object value = metaProperty.getProperty(entity);
- state[i] = value;
- persister.setPropertyValue(entity, i, value, EntityMode.POJO);
- }
- }
-
- public void onPreLoad(PreLoadEvent event) {
- if (preLoadEventCaller != null) {
- preLoadEventCaller.call(event.getEntity());
- }
- }
-
- public void onPostLoad(PostLoadEvent event) {
- if (postLoadEventListener != null) {
- postLoadEventListener.call(event.getEntity());
- }
- }
-
- public void onPostInsert(PostInsertEvent event) {
- if (postInsertEventListener != null) {
- postInsertEventListener.call(event.getEntity());
- }
- }
-
- public void onPostUpdate(PostUpdateEvent event) {
- if (postUpdateEventListener != null) {
- postUpdateEventListener.call(event.getEntity());
- }
- }
-
- public void onPostDelete(PostDeleteEvent event) {
- if (postDeleteEventListener != null) {
- postDeleteEventListener.call(event.getEntity());
- }
- }
-
- public boolean onPreDelete(PreDeleteEvent event) {
- if (preDeleteEventListener != null) {
- return preDeleteEventListener.call(event.getEntity());
- }
- return false;
- }
-
- public boolean onPreUpdate(PreUpdateEvent event) {
- Object entity = event.getEntity();
- boolean evict = false;
- if (preUpdateEventListener != null) {
- evict = preUpdateEventListener.call(entity);
- synchronizePersisterState(entity, event.getPersister(), event.getState());
- }
- if (lastUpdatedProperty != null && shouldTimestamp) {
- Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] { System
- .currentTimeMillis() });
- event.getState()[ArrayUtils.indexOf(event.getPersister().getPropertyNames(), GrailsDomainClassProperty.LAST_UPDATED)] = now;
- lastUpdatedProperty.setProperty(entity, now);
- }
- if (!AbstractSavePersistentMethod.isAutoValidationDisabled(entity)
- && !DefaultTypeTransformation.castToBoolean(validateMethod.invoke(entity,
- new Object[] { validateParams }))) {
- evict = true;
- if (failOnErrorEnabled) {
- Errors errors = (Errors) errorsProperty.getProperty(entity);
- throw new ValidationException("Validation error whilst flushing entity [" + entity.getClass().getName()
- + "]", errors);
- }
-
- }
- return evict;
- }
-
- private static abstract class EventTriggerCaller {
-
- public abstract boolean call(Object entity);
-
- boolean resolveReturnValue(Object retval) {
- if (retval instanceof Boolean) {
- return !((Boolean) retval).booleanValue();
- }
- return false;
- }
- }
-
- private static class MethodCaller extends EventTriggerCaller {
- Method method;
-
- MethodCaller(Method method) {
- this.method = method;
- }
-
- @Override
- public boolean call(Object entity) {
- Object retval = ReflectionUtils.invokeMethod(method, entity);
- return resolveReturnValue(retval);
- }
- }
-
- private static class MetaMethodCaller extends EventTriggerCaller {
- MetaMethod method;
-
- MetaMethodCaller(MetaMethod method) {
- this.method = method;
- }
-
- @Override
- public boolean call(Object entity) {
- Object retval = method.invoke(entity, EMPTY_OBJECT_ARRAY);
- return resolveReturnValue(retval);
- }
- }
-
- private static abstract class ClosureCaller extends EventTriggerCaller {
- boolean cloneFirst=false;
-
- Object callClosure(Object entity, Closure callable) {
- if (cloneFirst) {
- callable = (Closure)callable.clone();
- }
- callable.setResolveStrategy(Closure.DELEGATE_FIRST);
- callable.setDelegate(entity);
- Object retval = callable.call();
- return retval;
- }
- }
-
- private static class FieldClosureCaller extends ClosureCaller {
- Field field;
-
- FieldClosureCaller(Field field) {
- this.field = field;
- if (Modifier.isStatic(field.getModifiers())) {
- cloneFirst=true;
- }
- }
-
- @Override
- public boolean call(Object entity) {
- Object fieldval = ReflectionUtils.getField(field, entity);
- if (fieldval instanceof Closure) {
- return resolveReturnValue(callClosure(entity, (Closure) fieldval));
- }
- log.error("Field " + field + " is not Closure or method.");
- return false;
- }
- }
-
- private static class MetaPropertyClosureCaller extends ClosureCaller {
- MetaProperty metaProperty;
-
- MetaPropertyClosureCaller(MetaProperty metaProperty) {
- this.metaProperty = metaProperty;
- if (Modifier.isStatic(metaProperty.getModifiers())) {
- cloneFirst=true;
- }
- }
-
- @Override
- public boolean call(Object entity) {
- Object fieldval = metaProperty.getProperty(entity);
- if (fieldval instanceof Closure) {
- return resolveReturnValue(callClosure(entity, (Closure) fieldval));
- }
- log.error("Field " + metaProperty + " is not Closure.");
- return false;
- }
- }
+ PostInsertEventListener, PostUpdateEventListener, PostDeleteEventListener, PreDeleteEventListener,
+ PreUpdateEventListener {
+ private static final long serialVersionUID = 1L;
+ private static final Log log = LogFactory.getLog(ClosureEventListener.class);
+ private static final Object[] EMPTY_OBJECT_ARRAY = new Object[] {};
+
+ EventTriggerCaller saveOrUpdateCaller;
+ EventTriggerCaller beforeInsertCaller;
+ EventTriggerCaller preLoadEventCaller;
+ EventTriggerCaller postLoadEventListener;
+ EventTriggerCaller postInsertEventListener;
+ EventTriggerCaller postUpdateEventListener;
+ EventTriggerCaller postDeleteEventListener;
+ EventTriggerCaller preDeleteEventListener;
+ EventTriggerCaller preUpdateEventListener;
+ boolean shouldTimestamp = false;
+ MetaProperty dateCreatedProperty;
+ MetaProperty lastUpdatedProperty;
+ MetaClass domainMetaClass;
+ boolean failOnErrorEnabled = false;
+ MetaProperty errorsProperty;
+ @SuppressWarnings("unchecked")
+ Map validateParams;
+ MetaMethod validateMethod;
+
+ @SuppressWarnings("unchecked")
+ public ClosureEventListener(Class<?> domainClazz, boolean failOnError, List failOnErrorPackages) {
+ initialize(domainClazz, failOnError, failOnErrorPackages);
+ }
+
+ @SuppressWarnings("unchecked")
+ private void initialize(Class<?> domainClazz, boolean failOnError, List failOnErrorPackages) {
+ domainMetaClass = GroovySystem.getMetaClassRegistry().getMetaClass(domainClazz);
+ dateCreatedProperty = domainMetaClass.getMetaProperty(GrailsDomainClassProperty.DATE_CREATED);
+ lastUpdatedProperty = domainMetaClass.getMetaProperty(GrailsDomainClassProperty.LAST_UPDATED);
+ if (dateCreatedProperty != null || lastUpdatedProperty != null) {
+ Mapping m = GrailsDomainBinder.getMapping(domainClazz);
+ shouldTimestamp = (m != null && !m.isAutoTimestamp()) ? false : true;
+ }
+
+ saveOrUpdateCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.ONLOAD_SAVE);
+ beforeInsertCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_INSERT_EVENT);
+ preLoadEventCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.ONLOAD_EVENT);
+ if (preLoadEventCaller == null) {
+ preLoadEventCaller = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_LOAD_EVENT);
+ }
+ postLoadEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_LOAD_EVENT);
+ postInsertEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_INSERT_EVENT);
+ postUpdateEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_UPDATE_EVENT);
+ postDeleteEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.AFTER_DELETE_EVENT);
+ preDeleteEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_DELETE_EVENT);
+ preUpdateEventListener = buildCaller(domainClazz, ClosureEventTriggeringInterceptor.BEFORE_UPDATE_EVENT);
+
+ if(failOnErrorPackages.size() > 0) {
+ failOnErrorEnabled = GrailsClassUtils.isClassBelowPackage(domainClazz, failOnErrorPackages);
+ } else {
+ failOnErrorEnabled = failOnError;
+ }
+
+ validateParams = new HashMap();
+ validateParams.put(ValidatePersistentMethod.ARGUMENT_DEEP_VALIDATE, Boolean.FALSE);
+
+ errorsProperty = domainMetaClass.getMetaProperty(AbstractDynamicPersistentMethod.ERRORS_PROPERTY);
+
+ validateMethod = domainMetaClass.getMetaMethod(ValidatePersistentMethod.METHOD_SIGNATURE,
+ new Object[] { Map.class });
+ }
+
+ private EventTriggerCaller buildCaller(Class<?> domainClazz, String event) {
+ Method method = ReflectionUtils.findMethod(domainClazz, event);
+ if (method != null) {
+ ReflectionUtils.makeAccessible(method);
+ return new MethodCaller(method);
+ }
+
+ Field field = ReflectionUtils.findField(domainClazz, event);
+ if (field != null) {
+ ReflectionUtils.makeAccessible(field);
+ return new FieldClosureCaller(field);
+ }
+
+ MetaMethod metaMethod = domainMetaClass.getMetaMethod(event, EMPTY_OBJECT_ARRAY);
+ if (metaMethod != null) {
+ return new MetaMethodCaller(metaMethod);
+ }
+
+ MetaProperty metaProperty = domainMetaClass.getMetaProperty(event);
+ if (metaProperty != null) {
+ return new MetaPropertyClosureCaller(metaProperty);
+ }
+
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
+ Object entity = event.getObject();
+ boolean newEntity = !event.getSession().contains(entity);
+ if (newEntity) {
+ if (beforeInsertCaller != null) {
+ beforeInsertCaller.call(entity);
+ if (event.getSession().contains(entity)) {
+ EntityEntry entry = event.getEntry();
+ if (entry != null) {
+ Object[] state = entry.getLoadedState();
+ synchronizePersisterState(entity, entry.getPersister(), state);
+ }
+ }
+ }
+ if (shouldTimestamp) {
+ long time = System.currentTimeMillis();
+ if (dateCreatedProperty != null && newEntity) {
+ Object now = DefaultGroovyMethods.newInstance(dateCreatedProperty.getType(), new Object[] { time });
+ dateCreatedProperty.setProperty(entity, now);
+ }
+ if (lastUpdatedProperty != null) {
+ Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] { time });
+ lastUpdatedProperty.setProperty(entity, now);
+ }
+ }
+ }
+ }
+
+ private void synchronizePersisterState(Object entity, EntityPersister persister, Object[] state) {
+ String[] propertyNames = persister.getPropertyNames();
+ for (int i = 0; i < propertyNames.length; i++) {
+ String p = propertyNames[i];
+ MetaProperty metaProperty = domainMetaClass.getMetaProperty(p);
+ if (ClosureEventTriggeringInterceptor.IGNORED.contains(p) || metaProperty == null) {
+ continue;
+ }
+ Object value = metaProperty.getProperty(entity);
+ state[i] = value;
+ persister.setPropertyValue(entity, i, value, EntityMode.POJO);
+ }
+ }
+
+ public void onPreLoad(PreLoadEvent event) {
+ if(preLoadEventCaller != null) {
+ preLoadEventCaller.call(event.getEntity());
+ }
+ }
+
+ public void onPostLoad(PostLoadEvent event) {
+ if (postLoadEventListener != null) {
+ postLoadEventListener.call(event.getEntity());
+ }
+ }
+
+ public void onPostInsert(PostInsertEvent event) {
+ if (postInsertEventListener != null) {
+ postInsertEventListener.call(event.getEntity());
+ }
+ }
+
+ public void onPostUpdate(PostUpdateEvent event) {
+ if (postUpdateEventListener != null) {
+ postUpdateEventListener.call(event.getEntity());
+ }
+ }
+
+ public void onPostDelete(PostDeleteEvent event) {
+ if (postDeleteEventListener != null) {
+ postDeleteEventListener.call(event.getEntity());
+ }
+ }
+
+ public boolean onPreDelete(PreDeleteEvent event) {
+ if (preDeleteEventListener != null) {
+ return preDeleteEventListener.call(event.getEntity());
+ }
+ return false;
+ }
+
+ @SuppressWarnings("unchecked")
+ public boolean onPreUpdate(PreUpdateEvent event) {
+ Object entity = event.getEntity();
+ boolean evict = false;
+ if (preUpdateEventListener != null) {
+ evict = preUpdateEventListener.call(entity);
+ synchronizePersisterState(entity, event.getPersister(), event.getState());
+ }
+ if (lastUpdatedProperty != null && shouldTimestamp) {
+ Object now = DefaultGroovyMethods.newInstance(lastUpdatedProperty.getType(), new Object[] { System
+ .currentTimeMillis() });
+ event.getState()[ArrayUtils.indexOf(event.getPersister().getPropertyNames(), GrailsDomainClassProperty.LAST_UPDATED)] = now;
+ lastUpdatedProperty.setProperty(entity, now);
+ }
+ if (!AbstractSavePersistentMethod.isAutoValidationDisabled(entity)
+ && !DefaultTypeTransformation.castToBoolean(validateMethod.invoke(entity,
+ new Object[] { validateParams }))) {
+ evict = true;
+ if (failOnErrorEnabled) {
+ Errors errors = (Errors) errorsProperty.getProperty(entity);
+ throw new ValidationException("Validation error whilst flushing entity [" + entity.getClass().getName()
+ + "]", errors);
+ }
+
+ }
+ return evict;
+ }
+
+ private static abstract class EventTriggerCaller {
+ EventTriggerCaller() {
+
+ }
+
+ public abstract boolean call(Object entity);
+
+ boolean resolveReturnValue(Object retval) {
+ if (retval instanceof Boolean) {
+ return !((Boolean) retval).booleanValue();
+ } else {
+ return false;
+ }
+ }
+ }
+
+ private static class MethodCaller extends EventTriggerCaller {
+ Method method;
+
+ MethodCaller(Method method) {
+ this.method = method;
+ }
+
+ public boolean call(Object entity) {
+ Object retval = ReflectionUtils.invokeMethod(method, entity);
+ return resolveReturnValue(retval);
+ }
+ }
+
+ private static class MetaMethodCaller extends EventTriggerCaller {
+ MetaMethod method;
+
+ MetaMethodCaller(MetaMethod method) {
+ this.method = method;
+ }
+
+ public boolean call(Object entity) {
+ Object retval = method.invoke(entity, EMPTY_OBJECT_ARRAY);
+ return resolveReturnValue(retval);
+ }
+ }
+
+ private static abstract class ClosureCaller extends EventTriggerCaller {
+ boolean cloneFirst=false;
+
+ Object callClosure(Object entity, Closure callable) {
+ if(cloneFirst) {
+ callable=(Closure)callable.clone();
+ }
+ callable.setResolveStrategy(Closure.DELEGATE_FIRST);
+ callable.setDelegate(entity);
+ Object retval = callable.call();
+ return retval;
+ }
+ }
+
+ private static class FieldClosureCaller extends ClosureCaller {
+ Field field;
+
+ FieldClosureCaller(Field field) {
+ this.field = field;
+ if(Modifier.isStatic(field.getModifiers())) {
+ cloneFirst=true;
+ }
+ }
+
+ @Override
+ public boolean call(Object entity) {
+ Object fieldval = ReflectionUtils.getField(field, entity);
+ if (fieldval instanceof Closure) {
+ return resolveReturnValue(callClosure(entity, (Closure) fieldval));
+ } else {
+ log.error("Field " + field + " is not Closure or method.");
+ return false;
+ }
+ }
+ }
+
+ private static class MetaPropertyClosureCaller extends ClosureCaller {
+ MetaProperty metaProperty;
+
+ MetaPropertyClosureCaller(MetaProperty metaProperty) {
+ this.metaProperty = metaProperty;
+ if(Modifier.isStatic(metaProperty.getModifiers())) {
+ cloneFirst=true;
+ }
+ }
+
+ @Override
+ public boolean call(Object entity) {
+ Object fieldval = metaProperty.getProperty(entity);
+ if (fieldval instanceof Closure) {
+ return resolveReturnValue(callClosure(entity, (Closure) fieldval));
+ } else {
+ log.error("Field " + metaProperty + " is not Closure.");
+ return false;
+ }
+ }
+
+ }
}
View
173 ...a/org/codehaus/groovy/grails/orm/hibernate/support/ClosureEventTriggeringInterceptor.java
@@ -62,7 +62,6 @@
* @author Lari Hotari
* @since 1.0
*/
-@SuppressWarnings("rawtypes")
public class ClosureEventTriggeringInterceptor extends SaveOrUpdateEventListener implements ApplicationContextAware,
GrailsConfigurationAware,
PreLoadEventListener,
@@ -71,22 +70,22 @@
PostUpdateEventListener,
PostDeleteEventListener,
PreDeleteEventListener,
- PreUpdateEventListener {
- private static final long serialVersionUID = 1L;
- public static final Collection<String> IGNORED = new HashSet<String>(Arrays.asList(new String[]{"version", "id"}));
- public static final String ONLOAD_EVENT = "onLoad";
- public static final String ONLOAD_SAVE = "onSave";
- public static final String BEFORE_LOAD_EVENT = "beforeLoad";
- public static final String BEFORE_INSERT_EVENT = "beforeInsert";
- public static final String AFTER_INSERT_EVENT = "afterInsert";
- public static final String BEFORE_UPDATE_EVENT = "beforeUpdate";
- public static final String AFTER_UPDATE_EVENT = "afterUpdate";
- public static final String BEFORE_DELETE_EVENT = "beforeDelete";
- public static final String AFTER_DELETE_EVENT = "afterDelete";
- public static final String AFTER_LOAD_EVENT = "afterLoad";
-
- private transient ConcurrentMap<SoftKey<Class<?>>, ClosureEventListener> eventListeners = new ConcurrentHashMap<SoftKey<Class<?>>, ClosureEventListener>();
- private transient ConcurrentMap<SoftKey<Class<?>>, Boolean> cachedShouldTrigger = new ConcurrentHashMap<SoftKey<Class<?>>, Boolean>();
+ PreUpdateEventListener {
+ private static final long serialVersionUID = 1L;
+ public static final Collection<String> IGNORED = new HashSet<String>(Arrays.asList(new String[]{"version", "id"}));
+ public static final String ONLOAD_EVENT = "onLoad";
+ public static final String ONLOAD_SAVE = "onSave";
+ public static final String BEFORE_LOAD_EVENT = "beforeLoad";
+ public static final String BEFORE_INSERT_EVENT = "beforeInsert";
+ public static final String AFTER_INSERT_EVENT = "afterInsert";
+ public static final String BEFORE_UPDATE_EVENT = "beforeUpdate";
+ public static final String AFTER_UPDATE_EVENT = "afterUpdate";
+ public static final String BEFORE_DELETE_EVENT = "beforeDelete";
+ public static final String AFTER_DELETE_EVENT = "afterDelete";
+ public static final String AFTER_LOAD_EVENT = "afterLoad";
+
+ private transient ConcurrentMap<SoftKey<Class<?>>, ClosureEventListener> eventListeners = new ConcurrentHashMap<SoftKey<Class<?>>, ClosureEventListener>();
+ private transient ConcurrentMap<SoftKey<Class<?>>, Boolean> cachedShouldTrigger = new ConcurrentHashMap<SoftKey<Class<?>>, Boolean>();
boolean failOnError = false;
List failOnErrorPackages = Collections.EMPTY_LIST;
@@ -103,90 +102,90 @@ public void setConfiguration(ConfigObject co) {
}
private ClosureEventListener findEventListener(Object entity) {
- if(entity==null) return null;
- Class<?> clazz = entity.getClass();
-
- SoftKey<Class<?>> key = new SoftKey<Class<?>>(clazz);
- ClosureEventListener eventListener = eventListeners.get(key);
- if(eventListener == null) {
- Boolean shouldTrigger=cachedShouldTrigger.get(key);
- if(shouldTrigger==null || shouldTrigger) {
- synchronized(clazz) {
- eventListener = eventListeners.get(key);
- if(eventListener==null) {
- shouldTrigger = (entity != null && (GroovySystem.getMetaClassRegistry().getMetaClass(entity.getClass()) != null) && (DomainClassArtefactHandler.isDomainClass(clazz) ||
- AnnotationDomainClassArtefactHandler.isJPADomainClass(clazz)));
- if(shouldTrigger) {
- eventListener=new ClosureEventListener(clazz, failOnError, failOnErrorPackages);
- ClosureEventListener previous=eventListeners.putIfAbsent(key, eventListener);
- if(previous != null) {
- eventListener=previous;
- }
- }
- cachedShouldTrigger.put(key, shouldTrigger);
- }
- }
- }
- }
- return eventListener;
+ if(entity==null) return null;
+ Class<?> clazz = entity.getClass();
+
+ SoftKey<Class<?>> key = new SoftKey<Class<?>>(clazz);
+ ClosureEventListener eventListener = eventListeners.get(key);
+ if(eventListener == null) {
+ Boolean shouldTrigger=cachedShouldTrigger.get(key);
+ if(shouldTrigger==null || shouldTrigger) {
+ synchronized(clazz) {
+ eventListener = eventListeners.get(key);
+ if(eventListener==null) {
+ shouldTrigger = (entity != null && (GroovySystem.getMetaClassRegistry().getMetaClass(entity.getClass()) != null) && (DomainClassArtefactHandler.isDomainClass(clazz) ||
+ AnnotationDomainClassArtefactHandler.isJPADomainClass(clazz)));
+ if(shouldTrigger) {
+ eventListener=new ClosureEventListener(clazz, failOnError, failOnErrorPackages);
+ ClosureEventListener previous=eventListeners.putIfAbsent(key, eventListener);
+ if(previous != null) {
+ eventListener=previous;
+ }
+ }
+ cachedShouldTrigger.put(key, shouldTrigger);
+ }
+ }
+ }
+ }
+ return eventListener;
}
- @Override
- public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
- Object entity = event.getObject();
- ClosureEventListener eventListener=findEventListener(entity);
- if(eventListener != null) eventListener.onSaveOrUpdate(event);
- super.onSaveOrUpdate(event);
- }
+ public void onSaveOrUpdate(SaveOrUpdateEvent event) throws HibernateException {
+ Object entity = event.getObject();
+ ClosureEventListener eventListener=findEventListener(entity);
+ if(eventListener != null) eventListener.onSaveOrUpdate(event);
+ super.onSaveOrUpdate(event);
+ }
- public void onPreLoad(PreLoadEvent event) {
+ public void onPreLoad(PreLoadEvent event) {
Object entity = event.getEntity();
GrailsHibernateUtil.ensureCorrectGroovyMetaClass(entity, entity.getClass() );
- ClosureEventListener eventListener=findEventListener(entity);
- if(eventListener != null) eventListener.onPreLoad(event);
+ ClosureEventListener eventListener=findEventListener(entity);
+ if(eventListener != null) eventListener.onPreLoad(event);
}
- public void onPostLoad(PostLoadEvent event) {
+ public void onPostLoad(PostLoadEvent event) {
Object entity = event.getEntity();
- ClosureEventListener eventListener=findEventListener(entity);
- if(eventListener != null) {
- if(applicationContext != null && applicationContext.getAutowireCapableBeanFactory() != null) {
- applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(entity, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
- }
- eventListener.onPostLoad(event);
- }
+ ClosureEventListener eventListener=findEventListener(entity);
+ if(eventListener != null) {
+ if(applicationContext != null && applicationContext.getAutowireCapableBeanFactory() != null) {
+ applicationContext.getAutowireCapableBeanFactory().autowireBeanProperties(entity, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);
+ }
+ eventListener.onPostLoad(event);
+ }
}
- public void onPostInsert(PostInsertEvent event) {
- ClosureEventListener eventListener=findEventListener(event.getEntity());
- if(eventListener != null) eventListener.onPostInsert(event);
+ public void onPostInsert(PostInsertEvent event) {
+ ClosureEventListener eventListener=findEventListener(event.getEntity());
+ if(eventListener != null) eventListener.onPostInsert(event);
}
- public boolean onPreUpdate(PreUpdateEvent event) {
+ public boolean onPreUpdate(PreUpdateEvent event) {
boolean evict = false;
- ClosureEventListener eventListener=findEventListener(event.getEntity());
- if(eventListener != null) {
- evict = eventListener.onPreUpdate(event);
- }
+ ClosureEventListener eventListener=findEventListener(event.getEntity());
+ if(eventListener != null) {
+ evict = eventListener.onPreUpdate(event);
+ }
return evict;
}
- public void onPostUpdate(PostUpdateEvent event) {
- ClosureEventListener eventListener=findEventListener(event.getEntity());
- if(eventListener != null) eventListener.onPostUpdate(event);
+ public void onPostUpdate(PostUpdateEvent event) {
+ ClosureEventListener eventListener=findEventListener(event.getEntity());
+ if(eventListener != null) eventListener.onPostUpdate(event);
}
- public void onPostDelete(PostDeleteEvent event) {
- ClosureEventListener eventListener=findEventListener(event.getEntity());
- if(eventListener != null) eventListener.onPostDelete(event);
+ public void onPostDelete(PostDeleteEvent event) {
+ ClosureEventListener eventListener=findEventListener(event.getEntity());
+ if(eventListener != null) eventListener.onPostDelete(event);
}
- public boolean onPreDelete(PreDeleteEvent event) {
- ClosureEventListener eventListener=findEventListener(event.getEntity());
- if(eventListener != null) {
- return eventListener.onPreDelete(event);
- }
- return false;
+ public boolean onPreDelete(PreDeleteEvent event) {
+ ClosureEventListener eventListener=findEventListener(event.getEntity());
+ if(eventListener != null) {
+ return eventListener.onPreDelete(event);
+ } else {
+ return false;
+ }
}
private transient ApplicationContext applicationContext;
@@ -198,14 +197,14 @@ public void setApplicationContext(ApplicationContext applicationContext) {
// Support for Serialization, not sure if Hibernate really requires Serialization support for Interceptors
private void writeObject(java.io.ObjectOutputStream out) throws IOException {
- out.writeBoolean(failOnError);
- out.writeObject(failOnErrorPackages);
+ out.writeBoolean(failOnError);
+ out.writeObject(failOnErrorPackages);
}
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
- failOnError = in.readBoolean();
- failOnErrorPackages = (List) in.readObject();
- eventListeners = new ConcurrentHashMap<SoftKey<Class<?>>, ClosureEventListener>();
- cachedShouldTrigger = new ConcurrentHashMap<SoftKey<Class<?>>, Boolean>();
+ failOnError = in.readBoolean();
+ failOnErrorPackages = (List) in.readObject();
+ eventListeners = new ConcurrentHashMap<SoftKey<Class<?>>, ClosureEventListener>();
+ cachedShouldTrigger = new ConcurrentHashMap<SoftKey<Class<?>>, Boolean>();
}
}
View
4 .../codehaus/groovy/grails/orm/hibernate/support/HibernatePersistenceContextInterceptor.java
@@ -35,14 +35,12 @@
private SessionFactory sessionFactory;
private ThreadLocal<Boolean> participate = new ThreadLocal<Boolean>() {
- @Override
protected Boolean initialValue() {
- return Boolean.FALSE;
+ return Boolean.valueOf(false);
}
};
private ThreadLocal<Integer> nestingCount = new ThreadLocal<Integer>() {
- @Override
protected Integer initialValue() {
return Integer.valueOf(0);
}
View
39 src/java/org/codehaus/groovy/grails/orm/hibernate/support/SoftKey.java
@@ -3,16 +3,17 @@
import java.lang.ref.SoftReference;
/**
- * SoftReference key to be used with ConcurrentHashMap.
- *
+ *
+ * SoftReference key to be used with ConcurrentHashMap
+ *
* @author Lari Hotari
*/
-class SoftKey<T> extends SoftReference<T> {
- final int hash;
-
+class SoftKey<T> extends SoftReference<T>{
+ int hash;
+
public SoftKey(T referent) {
super(referent);
- hash = referent.hashCode();
+ this.hash=referent.hashCode();
}
@Override
@@ -22,30 +23,22 @@ public int hashCode() {
@Override
public boolean equals(Object obj) {
- if (this == obj) {
+ if (this == obj)
return true;
- }
- if (obj == null) {
+ if (obj == null)
return false;
- }
- if (getClass() != obj.getClass()) {
+ if (getClass() != obj.getClass())
return false;
- }
- @SuppressWarnings("unchecked")
- SoftKey<T> other = (SoftKey<T>)obj;
- if (hash != other.hash) {
+ SoftKey<T> other = (SoftKey<T>) obj;
+ if (hash != other.hash)
return false;
- }
- T referent = get();
- T otherReferent = other.get();
+ T referent=this.get();
+ T otherReferent=other.get();
if (referent == null) {
- if (otherReferent != null) {
+ if (otherReferent != null)
return false;
- }
- }
- else if (!referent.equals(otherReferent)) {
+ } else if (!referent.equals(otherReferent))
return false;
- }
return true;
}
}
View
17 src/java/org/codehaus/groovy/grails/plugins/codecs/HTMLCodec.java
@@ -15,24 +15,25 @@
package org.codehaus.groovy.grails.plugins.codecs;
import org.codehaus.groovy.grails.web.util.StreamCharBuffer;
-import org.springframework.web.context.request.RequestAttributes;
-import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.util.HtmlUtils;
+import org.springframework.web.context.request.RequestContextHolder;
+import org.springframework.web.context.request.RequestAttributes;
/**
- * Encodes and decodes strings to and from HTML.
- *
+ * A codec that encodes and decodes strings to and from HTML.
+ *
* @author Graeme Rocher
* @since 1.1
*/
public class HTMLCodec {
public static CharSequence encode(Object target) {
if (target != null) {
- if (target instanceof StreamCharBuffer) {
- return ((StreamCharBuffer)target).encodeAsHTML();
- }
- return HtmlUtils.htmlEscape(target.toString());
+ if(target instanceof StreamCharBuffer) {
+ return ((StreamCharBuffer)target).encodeAsHTML();
+ } else {
+ return HtmlUtils.htmlEscape(target.toString());
+ }
}
return null;
}
View
61 src/java/org/codehaus/groovy/grails/plugins/datasource/DataSourceGrailsPlugin.groovy
@@ -22,6 +22,7 @@ import grails.util.Metadata
import java.sql.Connection
import java.sql.Driver
import java.sql.DriverManager
+import java.sql.SQLException
import javax.sql.DataSource
import org.apache.commons.dbcp.BasicDataSource
@@ -33,7 +34,7 @@ import org.springframework.jdbc.datasource.TransactionAwareDataSourceProxy
import org.springframework.jndi.JndiObjectFactoryBean
/**
- * Handles the configuration of a DataSource within Grails.
+ * A plugin that handles the configuration of a DataSource within Grails.
*
* @author Graeme Rocher
* @since 0.4
@@ -68,10 +69,10 @@ class DataSourceGrailsPlugin {
}
def properties = {
- def driver = ds?.driverClassName ? ds.driverClassName : "org.h2.Driver"
+ def driver = ds?.driverClassName ? ds.driverClassName : "org.hsqldb.jdbcDriver"
driverClassName = driver
- url = ds?.url ? ds.url : "jdbc:h2:mem:grailsDB"
- boolean defaultDriver = (driver == "org.h2.Driver")
+ url = ds?.url ? ds.url : "jdbc:hsqldb:mem:grailsDB"
+ boolean defaultDriver = (driver == "org.hsqldb.jdbcDriver")
String theUsername = ds?.username ?: (defaultDriver ? "sa" : null)
if (theUsername != null) {
username = theUsername
@@ -158,39 +159,6 @@ class DataSourceGrailsPlugin {
dataSource(TransactionAwareDataSourceProxy, dataSourceUnproxied)
}
- def doWithWebDescriptor = { xml ->
-
- // only configure if explicitly enabled or in dev mode if not disabled
- def enabled = application.config.grails.dbconsole.enabled
- if (!(enabled instanceof Boolean)) {
- enabled = Environment.current == Environment.DEVELOPMENT
- }
- if (!enabled) {
- return
- }
-
- String urlPattern = (application.config.grails.dbconsole.urlRoot ?: '/dbconsole') + '/*'
-
- def listeners = xml.'listener'
-
- listeners[listeners.size() - 1] + {
- 'servlet' {
- 'servlet-name'('H2Console')
- 'servlet-class'('org.h2.server.web.WebServlet')
- 'init-param' {
- 'param-name'('-webAllowOthers')
- 'param-value'('true')
- }
- 'load-on-startup'('2')
- }
-
- 'servlet-mapping' {
- 'servlet-name'('H2Console')
- 'url-pattern'(urlPattern)
- }
- }
- }
-
def onChange = {
restartContainer()
}
@@ -204,27 +172,28 @@ class DataSourceGrailsPlugin {
Connection connection
try {
connection = dataSource.getConnection()
- def dbName = connection.metaData.databaseProductName
- if (dbName == 'HSQL Database Engine' || dbName == 'H2') {
+ def dbName =connection.metaData.databaseProductName
+ if (dbName == 'HSQL Database Engine') {
connection.createStatement().executeUpdate('SHUTDOWN')
}
- }
- finally {
- try { connection?.close() } catch (ignored) {}
+ } finally {
+ connection?.close()
}
}
- if (Metadata.current.isWarDeployed()) {
+ if (Metadata.current.warDeployed) {
deregisterJDBCDrivers()
}
}
private void deregisterJDBCDrivers() {
- DriverManager.drivers.each { Driver driver ->
+ Enumeration<Driver> drivers = DriverManager.getDrivers()
+ while (drivers.hasMoreElements()) {
+ Driver driver = drivers.nextElement()
try {
DriverManager.deregisterDriver(driver)
- } catch (e) {
- log.error "Error deregistering JDBC driver [$driver]: $e.message", e
+ } catch (SQLException e) {
+ log.error("Error deregistering JDBC driver ["+driver+"]: " + e.getMessage(), e)
}
}
}
View
5 src/java/org/codehaus/groovy/grails/plugins/web/ControllersGrailsPlugin.groovy
@@ -15,7 +15,6 @@
*/
package org.codehaus.groovy.grails.plugins.web
-import grails.util.Environment
import grails.util.GrailsUtil
import java.lang.reflect.Modifier
@@ -107,10 +106,10 @@ class ControllersGrailsPlugin {
}
}
- def doWithWebDescriptor = { webXml ->
+ def doWithWebDescriptor = {webXml ->
def basedir = System.getProperty("base.dir")
- def grailsEnv = Environment.current.name
+ def grailsEnv = GrailsUtil.getEnvironment()
def mappingElement = webXml.'servlet-mapping'
mappingElement = mappingElement[mappingElement.size() - 1]
View
3 src/java/org/codehaus/groovy/grails/resolve/IvyDependencyManager.groovy
@@ -307,8 +307,7 @@ class IvyDependencyManager extends AbstractIvyDependencyManager implements Depen
// data source
"${runtimeDependenciesMethod}" "commons-dbcp:commons-dbcp:1.2.2",
"commons-pool:commons-pool:1.5.3",
- "hsqldb:hsqldb:1.8.0.10",
- "com.h2database:h2:1.2.144"
+ "hsqldb:hsqldb:1.8.0.10"
// caching
"${runtimeDependenciesMethod}" ("net.sf.ehcache:ehcache-core:1.7.1") {
View
21 src/java/org/codehaus/groovy/grails/support/ResourceAwareTemplateEngine.java
@@ -40,8 +40,11 @@
*
* @author Graeme Rocher
* @since 0.4
+ * <p/>
+ * Created: Feb 22, 2007
+ * Time: 6:37:08 PM
*/
-public abstract class ResourceAwareTemplateEngine extends TemplateEngine {
+abstract public class ResourceAwareTemplateEngine extends TemplateEngine {
/**
* Creates the specified Template using the given Spring Resource
*
@@ -50,12 +53,11 @@
* @throws IOException Thrown when there was an error reading the Template
* @throws ClassNotFoundException Thrown when there was a problem loading the Template into a class
*/
- @SuppressWarnings("unused")
public Template createTemplate(Resource resource) throws IOException, ClassNotFoundException {
return createTemplateAndCloseInput(resource.getInputStream());
}
- /**
+ /**
* Creates the specified Template using the given Spring Resource
*
* @param resource The Spring Resource to create the template for
@@ -64,12 +66,11 @@ public Template createTemplate(Resource resource) throws IOException, ClassNotFo
* @throws IOException Thrown when there was an error reading the Template
* @throws ClassNotFoundException Thrown when there was a problem loading the Template into a class
*/
- public abstract Template createTemplate(Resource resource, boolean cacheable);
+ abstract public Template createTemplate(Resource resource, boolean cacheable);
- @Override
public final Template createTemplate(Reader reader) throws IOException {
- StreamByteBuffer buf=new StreamByteBuffer();
- IOUtils.copy(reader, new OutputStreamWriter(buf.getOutputStream(), GroovyPageParser.GROOVY_SOURCE_CHAR_ENCODING));
+ StreamByteBuffer buf=new StreamByteBuffer();
+ IOUtils.copy(reader, new OutputStreamWriter(buf.getOutputStream(), GroovyPageParser.GROOVY_SOURCE_CHAR_ENCODING));
return createTemplate(buf.getInputStream());
}
/**
@@ -80,7 +81,7 @@ public final Template createTemplate(Reader reader) throws IOException {
* @return A Template instance
* @throws IOException Thrown when an IO error occurs reading the stream
*/
- public abstract Template createTemplate(InputStream inputStream) throws IOException;
+ abstract public Template createTemplate(InputStream inputStream) throws IOException;
@Override
public Template createTemplate(String templateText) throws CompilationFailedException, ClassNotFoundException, IOException {
@@ -97,11 +98,11 @@ public Template createTemplate(URL url) throws CompilationFailedException, Class
return createTemplateAndCloseInput(url.openStream());
}
- private Template createTemplateAndCloseInput(InputStream input) throws FileNotFoundException, IOException {
+ private Template createTemplateAndCloseInput(InputStream input) throws FileNotFoundException, IOException {
try {
return createTemplate(input);
} finally {
DefaultGroovyMethodsSupport.closeWithWarning(input);
}
- }
+ }
}
View
10 src/java/org/codehaus/groovy/grails/web/context/GrailsConfigUtils.java
@@ -177,12 +177,12 @@ public static GrailsRuntimeConfigurator determineGrailsRuntimeConfiguratorFromSe
* @return
*/
public static boolean isConfigTrue(GrailsApplication application, String propertyName) {
- return ((application != null && application.getFlatConfig() != null && DefaultTypeTransformation.castToBoolean(application.getFlatConfig().get(propertyName))) ||
- Boolean.getBoolean(propertyName));
- }
+ return ((application != null && application.getFlatConfig() != null && DefaultTypeTransformation.castToBoolean(application.getFlatConfig().get(propertyName))) ||
+ Boolean.getBoolean(propertyName));
+ }
// support GrailsApplication mocking, see ControllersGrailsPluginTests
- public static boolean isConfigTrue(@SuppressWarnings("unused")Object application, @SuppressWarnings("unused")String propertyName) {
- return false;
+ public static boolean isConfigTrue(Object application, String propertyName) {
+ return false;
}
}
View
100 src/java/org/codehaus/groovy/grails/web/mapping/DefaultUrlMappingsHolder.java
@@ -56,10 +56,10 @@
private Map<String, UrlMappingInfo> cachedMatches;
private Map<String, List<UrlMappingInfo>> cachedListMatches;
private enum CustomListWeigher implements Weigher<List<UrlMappingInfo>> {
- INSTANCE;
- public int weightOf(List<UrlMappingInfo> values) {
- return values.size() + 1;
- }
+ INSTANCE;
+ public int weightOf(List<UrlMappingInfo> values) {
+ return values.size() + 1;
+ }
}
private List<UrlMapping> urlMappings = new ArrayList<UrlMapping>();
@@ -84,14 +84,14 @@ public DefaultUrlMappingsHolder(List<UrlMapping> mappings) {
}
public DefaultUrlMappingsHolder(List<UrlMapping> mappings, List excludePatterns) {
- this(mappings, excludePatterns, false);
+ this(mappings, excludePatterns, false);
}
public DefaultUrlMappingsHolder(List<UrlMapping> mappings, List excludePatterns, boolean doNotCallInit) {
urlMappings = mappings;
this.excludePatterns = excludePatterns;
if(!doNotCallInit) {
- initialize();
+ initialize();
}
}
@@ -106,7 +106,7 @@ public void initialize() {
.weigher(CustomListWeigher.INSTANCE)
.build();
if(urlCreatorMaxWeightedCacheCapacity > 0) {
- urlCreatorCache = new UrlCreatorCache(urlCreatorMaxWeightedCacheCapacity);
+ urlCreatorCache = new UrlCreatorCache(urlCreatorMaxWeightedCacheCapacity);
}
mappings = urlMappings.toArray(new UrlMapping[urlMappings.size()]);
@@ -160,24 +160,24 @@ public void initialize() {
}
}
- @SuppressWarnings("unchecked")
- private void sortMappings() {
- List<ResponseCodeUrlMapping> responseCodeUrlMappings = new ArrayList<ResponseCodeUrlMapping>();
- Iterator<UrlMapping> iter = urlMappings.iterator();
- while (iter.hasNext()) {
- UrlMapping mapping = iter.next();
- if (mapping instanceof ResponseCodeUrlMapping) {
- responseCodeUrlMappings.add((ResponseCodeUrlMapping)mapping);
- iter.remove();
- }
- }
-
- Collections.sort(urlMappings);
- urlMappings.addAll(responseCodeUrlMappings);
- Collections.reverse(urlMappings);
- }
-
- public UrlMapping[] getUrlMappings() {
+ @SuppressWarnings("unchecked")
+ private void sortMappings() {
+ List<ResponseCodeUrlMapping> responseCodeUrlMappings = new ArrayList<ResponseCodeUrlMapping>();
+ Iterator<UrlMapping> iter = urlMappings.iterator();
+ while (iter.hasNext()) {
+ UrlMapping mapping = iter.next();
+ if (mapping instanceof ResponseCodeUrlMapping) {
+ responseCodeUrlMappings.add((ResponseCodeUrlMapping)mapping);
+ iter.remove();
+ }
+ }
+
+ Collections.sort(urlMappings);
+ urlMappings.addAll(responseCodeUrlMappings);
+ Collections.reverse(urlMappings);
+ }
+
+ public UrlMapping[] getUrlMappings() {
return mappings;
}
@@ -188,28 +188,29 @@ public List getExcludePatterns() {
/**
* @see UrlMappingsHolder#getReverseMapping(String, String, java.util.Map)
*/
+ @SuppressWarnings("unchecked")
public UrlCreator getReverseMapping(final String controller, final String action, Map params) {
if (params == null) params = Collections.EMPTY_MAP;
if(urlCreatorCache != null) {
- UrlCreatorCache.ReverseMappingKey key=urlCreatorCache.createKey(controller, action, params);
- UrlCreator creator=urlCreatorCache.lookup(key);
- if(creator==null) {
- creator=resolveUrlCreator(controller, action, params);
- creator=urlCreatorCache.putAndDecorate(key, creator);
- }
- // preserve previous side-effect, remove mappingName from params
- params.remove("mappingName");
- return creator;
+ UrlCreatorCache.ReverseMappingKey key=urlCreatorCache.createKey(controller, action, params);
+ UrlCreator creator=urlCreatorCache.lookup(key);
+ if(creator==null) {
+ creator=resolveUrlCreator(controller, action, params);
+ creator=urlCreatorCache.putAndDecorate(key, creator);
+ }
+ // preserve previous side-effect, remove mappingName from params
+ params.remove("mappingName");
+ return creator;
+ } else {
+ // cache is disabled
+ return resolveUrlCreator(controller, action, params);
}
- // cache is disabled
- return resolveUrlCreator(controller, action, params);
}
- @SuppressWarnings("unchecked")
- private UrlCreator resolveUrlCreator(final String controller,
- final String action, Map params) {
- UrlMapping mapping = null;
+ private UrlCreator resolveUrlCreator(final String controller,
+ final String action, Map params) {
+ UrlMapping mapping = null;
mapping = namedMappings.get(params.remove("mappingName"));
if (mapping == null) {
@@ -243,12 +244,12 @@ private UrlCreator resolveUrlCreator(final String controller,
}
UrlCreator creator;
if (mapping == null || (mapping instanceof ResponseCodeUrlMapping)) {
- creator=new DefaultUrlCreator(controller, action);
+ creator=new DefaultUrlCreator(controller, action);
} else {
- creator=mapping;
+ creator=mapping;
}
return creator;
- }
+ }
/**
* Performs a match uses reverse mappings to looks up a mapping from the
@@ -520,11 +521,12 @@ public void put(UrlMappingsListKey key, UrlMappingKey mapping) {
}
}
- public void setMaxWeightedCacheCapacity(int maxWeightedCacheCapacity) {
- this.maxWeightedCacheCapacity = maxWeightedCacheCapacity;
- }
+ public void setMaxWeightedCacheCapacity(int maxWeightedCacheCapacity) {
+ this.maxWeightedCacheCapacity = maxWeightedCacheCapacity;
+ }
- public void setUrlCreatorMaxWeightedCacheCapacity(int urlCreatorMaxWeightedCacheCapacity) {
- this.urlCreatorMaxWeightedCacheCapacity = urlCreatorMaxWeightedCacheCapacity;
- }
+ public void setUrlCreatorMaxWeightedCacheCapacity(
+ int urlCreatorMaxWeightedCacheCapacity) {
+ this.urlCreatorMaxWeightedCacheCapacity = urlCreatorMaxWeightedCacheCapacity;
+ }
}
View
251 src/java/org/codehaus/groovy/grails/web/mapping/UrlCreatorCache.java
@@ -23,279 +23,264 @@
* @author Lari Hotari
* @since 1.3.5
*/
-@SuppressWarnings({ "unchecked", "rawtypes" })
public class UrlCreatorCache {
private final ConcurrentMap<ReverseMappingKey, CachingUrlCreator> cacheMap;
-
- private enum CachingUrlCreatorWeigher implements Weigher<CachingUrlCreator> {
- INSTANCE;
- public int weightOf(CachingUrlCreator cachingUrlCreator) {
- return cachingUrlCreator.weight() + 1;
- }
- }
-
+ private enum CachingUrlCreatorWeigher implements Weigher<CachingUrlCreator> {
+ INSTANCE;
+ public int weightOf(CachingUrlCreator cachingUrlCreator) {
+ return cachingUrlCreator.weight() + 1;
+ }
+ }
+
public UrlCreatorCache(int maxSize) {
cacheMap = new ConcurrentLinkedHashMap.Builder<ReverseMappingKey, CachingUrlCreator>()
- .maximumWeightedCapacity(maxSize).weigher(CachingUrlCreatorWeigher.INSTANCE).build();
+ .maximumWeightedCapacity(maxSize)
+ .weigher(CachingUrlCreatorWeigher.INSTANCE)
+ .build();
}
-
+
public void clear() {
cacheMap.clear();
}
-
+
public ReverseMappingKey createKey(String controller, String action, Map params) {
return new ReverseMappingKey(controller, action, params);
}
-
+
public UrlCreator lookup(ReverseMappingKey key) {
return cacheMap.get(key);
}
-
+
public UrlCreator putAndDecorate(ReverseMappingKey key, UrlCreator delegate) {
- CachingUrlCreator cachingUrlCreator = new CachingUrlCreator(delegate, key.weight() * 2);
- CachingUrlCreator prevCachingUrlCreator = cacheMap.putIfAbsent(key, cachingUrlCreator);
- if (prevCachingUrlCreator != null) {
+ CachingUrlCreator cachingUrlCreator=new CachingUrlCreator(delegate, key.weight() * 2);
+ CachingUrlCreator prevCachingUrlCreator=cacheMap.putIfAbsent(key, cachingUrlCreator);
+ if(prevCachingUrlCreator != null) {
return prevCachingUrlCreator;
+ } else {
+ return cachingUrlCreator;
}
- return cachingUrlCreator;
}
private class CachingUrlCreator implements UrlCreator {
private UrlCreator delegate;
- private ConcurrentHashMap<UrlCreatorKey, String> cache = new ConcurrentHashMap<UrlCreatorKey, String>();
+ private ConcurrentHashMap<UrlCreatorKey, String> cache=new ConcurrentHashMap<UrlCreatorKey, String>();
private final int weight;
-
+
public CachingUrlCreator(UrlCreator delegate, int weight) {
- this.delegate = delegate;
- this.weight = weight;
+ this.delegate=delegate;
+ this.weight=weight;
}
public int weight() {
return weight;
}
- public String createRelativeURL(String controller, String action, Map parameterValues,
- String encoding, String fragment) {
- UrlCreatorKey key = new UrlCreatorKey(controller, action, parameterValues, encoding, fragment, 0);
- String url = cache.get(key);
- if (url == null) {
- url = delegate.createRelativeURL(controller, action, parameterValues, encoding, fragment);
+ public String createRelativeURL(String controller, String action,
+ Map parameterValues, String encoding, String fragment) {
+ UrlCreatorKey key=new UrlCreatorKey(controller, action, parameterValues, encoding, fragment, 0);
+ String url=cache.get(key);
+ if(url==null) {
+ url=delegate.createRelativeURL(controller, action, parameterValues, encoding, fragment);
cache.put(key, url);
}
return url;
}
- public String createRelativeURL(String controller, String action, Map parameterValues, String encoding) {
- UrlCreatorKey key = new UrlCreatorKey(controller, action, parameterValues, encoding, null, 0);
- String url = cache.get(key);
- if (url == null) {
- url = delegate.createRelativeURL(controller, action, parameterValues, encoding);
+ public String createRelativeURL(String controller, String action,
+ Map parameterValues, String encoding) {
+ UrlCreatorKey key=new UrlCreatorKey(controller, action, parameterValues, encoding, null, 0);
+ String url=cache.get(key);
+ if(url==null) {
+ url=delegate.createRelativeURL(controller, action, parameterValues, encoding);
cache.put(key, url);
}
return url;
}
- public String createURL(String controller, String action, Map parameterValues, String encoding, String fragment) {
- UrlCreatorKey key = new UrlCreatorKey(controller, action, parameterValues, encoding, fragment, 1);
- String url = cache.get(key);
- if (url == null) {
- url = delegate.createURL(controller, action, parameterValues, encoding, fragment);
+ public String createURL(String controller, String action,
+ Map parameterValues, String encoding, String fragment) {
+ UrlCreatorKey key=new UrlCreatorKey(controller, action, parameterValues, encoding, fragment, 1);
+ String url=cache.get(key);
+ if(url==null) {
+ url=delegate.createURL(controller, action, parameterValues, encoding, fragment);
cache.put(key, url);
}
return url;
}
- public String createURL(String controller, String action, Map parameterValues, String encoding) {
- UrlCreatorKey key = new UrlCreatorKey(controller, action, parameterValues, encoding, null, 1);
- String url = cache.get(key);
- if (url == null) {
- url = delegate.createURL(controller, action, parameterValues, encoding);
+ public String createURL(String controller, String action,
+ Map parameterValues, String encoding) {
+ UrlCreatorKey key=new UrlCreatorKey(controller, action, parameterValues, encoding, null, 1);
+ String url=cache.get(key);
+ if(url==null) {
+ url=delegate.createURL(controller, action, parameterValues, encoding);
cache.put(key, url);
}
return url;
}
// don't cache these methods at all
-
- public String createURL(Map parameterValues, String encoding, String fragment) {
+
+ public String createURL(Map parameterValues, String encoding,
+ String fragment) {
return delegate.createURL(parameterValues, encoding, fragment);
}
public String createURL(Map parameterValues, String encoding) {
return delegate.createURL(parameterValues, encoding);
}
}
-
+
public static class ReverseMappingKey {
protected final String controller;
protected final String action;
protected final String[] paramKeys;
protected final String[] paramValues;
-
- public ReverseMappingKey(String controller, String action, Map<Object, Object> params) {
- this.controller = controller;
- this.action = action;
- if (params != null) {
- paramKeys = new String[params.size()];
- paramValues = new String[params.size()];
- int i = 0;
- for (Map.Entry entry : params.entrySet()) {
- paramKeys[i] = String.valueOf(entry.getKey());
- String value = null;
- if (entry.getValue() instanceof CharSequence) {
- value = String.valueOf(entry.getValue());
- }
- else if (entry.getValue() instanceof Collection) {
+
+ public ReverseMappingKey(String controller, String action, Map<Object,Object> params) {
+ this.controller=controller;
+ this.action=action;
+ if(params != null) {
+ paramKeys=new String[params.size()];
+ paramValues=new String[params.size()];
+ int i=0;
+ for(Map.Entry entry : params.entrySet()) {
+ paramKeys[i]=String.valueOf(entry.getKey());
+ String value=null;
+ if(entry.getValue() instanceof CharSequence) {
+ value=String.valueOf(entry.getValue());
+ } else if(entry.getValue() instanceof Collection) {
StringUtils.join((Collection)entry.getValue(), ',');
- }
- else if (entry.getValue() instanceof Object[]) {
+ } else if (entry.getValue() instanceof Object[]) {
StringUtils.join((Object[])entry.getValue(), ',');
+ } else {
+ value=String.valueOf(entry.getValue());
}
- else {
- value = String.valueOf(entry.getValue());
- }
- paramValues[i] = value;
+ paramValues[i]=value;
i++;
}
- }
- else {
- paramKeys = new String[0];
- paramValues = new String[0];
+ } else {
+ paramKeys=new String[0];
+ paramValues=new String[0];
}
}
public int weight() {
- int weight = 0;
+ int weight=0;
weight += (controller != null) ? controller.length() : 0;
weight += (action != null) ? action.length() : 0;
- for (int i = 0; i < paramKeys.length; i++) {
+ for(int i=0; i < paramKeys.length;i++) {
weight += (paramKeys[i] != null) ? paramKeys[i].length() : 0;
}
- for (int i = 0; i < paramValues.length; i++) {
+ for(int i=0; i < paramValues.length;i++) {
weight += (paramValues[i] != null) ? paramValues[i].length() : 0;
}
return weight;
}
-
+
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
- result = prime * result + ((action == null) ? 0 : action.hashCode());
- result = prime * result + ((controller == null) ? 0 : controller.hashCode());
+ result = prime * result
+ + ((action == null) ? 0 : action.hashCode());
+ result = prime * result
+ + ((controller == null) ? 0 : controller.hashCode());
result = prime * result + Arrays.hashCode(paramKeys);
result = prime * result + Arrays.hashCode(paramValues);
return result;
}
@Override
public boolean equals(Object obj) {
- if (this == obj) {
+ if (this == obj)
return true;
- }
- if (obj == null) {
+ if (obj == null)
return false;
- }
- if (getClass() != obj.getClass()) {
+ if (getClass() != obj.getClass())
return false;
- }
- ReverseMappingKey other = (ReverseMappingKey)obj;
+ ReverseMappingKey other = (ReverseMappingKey) obj;
if (action == null) {
- if (other.action != null) {
+ if (other.action != null)
return false;
- }
- }
- else if (!action.equals(other.action)) {
+ } else if (!action.equals(other.action))
return false;
- }
if (controller == null) {
- if (other.controller != null) {
+ if (other.controller != null)
return false;
- }
- }
- else if (!controller.equals(other.controller)) {
+ } else if (!controller.equals(other.controller))
return false;
- }
- if (!Arrays.equals(paramKeys, other.paramKeys)) {
+ if (!Arrays.equals(paramKeys, other.paramKeys))
return false;
- }
- if (!Arrays.equals(paramValues, other.paramValues)) {
+ if (!Arrays.equals(paramValues, other.paramValues))
return false;
- }
return true;
}
@Override
public String toString() {
- return "UrlCreatorCache.ReverseMappingKey [action=" + action + ", controller=" + controller +
- ", paramKeys=" + Arrays.toString(paramKeys) + ", paramValues=" +
- Arrays.toString(paramValues) + "]";
+ return "UrlCreatorCache.ReverseMappingKey [action=" + action + ", controller="
+ + controller + ", paramKeys=" + Arrays.toString(paramKeys)
+ + ", paramValues=" + Arrays.toString(paramValues) + "]";
}
}
-
+
private static class UrlCreatorKey extends ReverseMappingKey {
protected final String encoding;
protected final String fragment;
protected final int urlType;
-
- public UrlCreatorKey(String controller, String action, Map<Object, Object> params, String encoding,
- String fragment, int urlType) {
+
+ public UrlCreatorKey(String controller, String action,
+ Map<Object, Object> params, String encoding, String fragment, int urlType) {
super(controller, action, params);
- this.encoding = (encoding != null) ? encoding.toLowerCase() : null;
- this.fragment = fragment;
- this.urlType = urlType;
+ this.encoding=(encoding != null) ? encoding.toLowerCase() : null;
+ this.fragment=fragment;
+ this.urlType=urlType;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
- result = prime * result + ((encoding == null) ? 0 : encoding.hashCode());
- result = prime * result + ((fragment == null) ? 0 : fragment.hashCode());
+ result = prime * result
+ + ((encoding == null) ? 0 : encoding.hashCode());
+ result = prime * result
+ + ((fragment == null) ? 0 : fragment.hashCode());
result = prime * result + urlType;
return result;
}