/
DomainClassGrailsPlugin.groovy
405 lines (372 loc) · 16.9 KB
/
DomainClassGrailsPlugin.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
/*
* Copyright 2004-2005 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.codehaus.groovy.grails.plugins
import grails.artefact.Enhanced
import grails.util.GrailsUtil
import grails.validation.ValidationErrors
import org.codehaus.groovy.grails.commons.ComponentCapableDomainClass
import org.codehaus.groovy.grails.commons.DomainClassArtefactHandler
import org.codehaus.groovy.grails.commons.GrailsApplication
import org.codehaus.groovy.grails.commons.GrailsClassUtils
import org.codehaus.groovy.grails.commons.GrailsDomainClass
import org.codehaus.groovy.grails.commons.GrailsDomainConfigurationUtil
import org.codehaus.groovy.grails.domain.GormApiSupport
import org.codehaus.groovy.grails.domain.GrailsDomainClassCleaner
import org.codehaus.groovy.grails.domain.GrailsDomainClassMappingContext
import org.codehaus.groovy.grails.support.SoftThreadLocalMap
import org.codehaus.groovy.grails.validation.ConstraintEvalUtils
import org.codehaus.groovy.grails.validation.ConstraintsEvaluator
import org.codehaus.groovy.grails.validation.ConstraintsEvaluatorFactoryBean
import org.codehaus.groovy.grails.validation.GrailsDomainClassValidator
import org.grails.datastore.mapping.model.MappingContext
import org.grails.datastore.mapping.reflect.ClassPropertyFetcher
import org.grails.datastore.mapping.simple.SimpleMapDatastore
import org.springframework.beans.BeanUtils
import org.springframework.beans.factory.config.AutowireCapableBeanFactory
import org.springframework.beans.factory.config.MethodInvokingFactoryBean
import org.springframework.context.ApplicationContext
import org.springframework.context.ConfigurableApplicationContext
import org.springframework.validation.BeanPropertyBindingResult
import org.springframework.validation.Errors
import org.springframework.validation.Validator
/**
* Configures the domain classes in the spring context.
*
* @author Graeme Rocher
* @since 0.4
*/
class DomainClassGrailsPlugin {
def watchedResources = ["file:./grails-app/domain/**/*.groovy",
"file:./plugins/*/grails-app/domain/**/*.groovy"]
def version = GrailsUtil.getGrailsVersion()
def dependsOn = [i18n:version]
def loadAfter = ['controllers']
def doWithSpring = {
def config = application.config
def defaultConstraintsMap = getDefaultConstraints(config)
"${ConstraintsEvaluator.BEAN_NAME}"(ConstraintsEvaluatorFactoryBean) {
defaultConstraints = defaultConstraintsMap
}
grailsDomainClassMappingContext(GrailsDomainClassMappingContext, application)
grailsDomainClassCleaner(GrailsDomainClassCleaner, application)
for (dc in application.domainClasses) {
// Note the use of Groovy's ability to use dynamic strings in method names!
if (dc.abstract) {
continue
}
"${dc.fullName}"(dc.clazz) { bean ->
bean.singleton = false
bean.autowire = "byName"
}
"${dc.fullName}DomainClass"(MethodInvokingFactoryBean) { bean ->
targetObject = ref("grailsApplication", true)
targetMethod = "getArtefact"
bean.lazyInit = true
arguments = [DomainClassArtefactHandler.TYPE, dc.fullName]
}
"${dc.fullName}PersistentClass"(MethodInvokingFactoryBean) { bean ->
targetObject = ref("${dc.fullName}DomainClass")
bean.lazyInit = true
targetMethod = "getClazz"
}
"${dc.fullName}Validator"(GrailsDomainClassValidator) { bean ->
messageSource = ref("messageSource")
bean.lazyInit = true
domainClass = ref("${dc.fullName}DomainClass")
grailsApplication = ref("grailsApplication", true)
}
}
}
static getDefaultConstraints(ConfigObject config) {
ConstraintEvalUtils.getDefaultConstraints(config)
}
static final PROPERTY_INSTANCE_MAP = new SoftThreadLocalMap()
def doWithDynamicMethods = { ApplicationContext ctx->
enhanceDomainClasses(application, ctx)
}
def onChange = { event ->
def cls = event.source
try {
ClassPropertyFetcher.@cachedClassPropertyFetchers.clear()
} catch (e) {
// restricted environment, ignore
}
if (!(cls instanceof Class)) {
return
}
final domainClass = application.addArtefact(DomainClassArtefactHandler.TYPE, cls)
if (domainClass.abstract) {
return
}
def beans = beans {
"${domainClass.fullName}"(domainClass.clazz) { bean ->
bean.singleton = false
bean.autowire = "byName"
}
"${domainClass.fullName}DomainClass"(MethodInvokingFactoryBean) { bean ->
targetObject = ref("grailsApplication", true)
targetMethod = "getArtefact"
bean.lazyInit = true
arguments = [DomainClassArtefactHandler.TYPE, domainClass.fullName]
}
"${domainClass.fullName}PersistentClass"(MethodInvokingFactoryBean) { bean ->
targetObject = ref("${domainClass.fullName}DomainClass")
bean.lazyInit = true
targetMethod = "getClazz"
}
"${domainClass.fullName}Validator"(GrailsDomainClassValidator) { bean ->
messageSource = ref("messageSource")
bean.lazyInit = true
domainClass = ref("${domainClass.fullName}DomainClass")
grailsApplication = ref("grailsApplication", true)
}
}
beans.registerBeans(event.ctx)
enhanceDomainClasses(event.application, event.ctx)
event.application.refreshConstraints()
}
def onConfigChange = { event ->
ConstraintEvalUtils.clearDefaultConstraints()
def beans = beans {
def defaultConstraintsMap = getDefaultConstraints(event.source)
"${ConstraintsEvaluator.BEAN_NAME}"(ConstraintsEvaluatorFactoryBean) {
defaultConstraints = defaultConstraintsMap
}
}
beans.registerBeans(event.ctx)
event.application.refreshConstraints()
}
static enhanceDomainClasses(GrailsApplication application, ApplicationContext ctx) {
for (GrailsDomainClass dc in application.domainClasses) {
def domainClass = dc
def isEnhanced = dc.clazz.getAnnotation(Enhanced) != null
if (dc instanceof ComponentCapableDomainClass) {
for (GrailsDomainClass component in dc.getComponents()) {
if (!application.isDomainClass(component.clazz)) {
registerConstraintsProperty(component.metaClass, component)
}
}
}
MetaClass metaClass = domainClass.metaClass
registerConstraintsProperty(metaClass, domainClass)
addRelationshipManagementMethods(domainClass, ctx)
metaClass.getDomainClass = {-> domainClass }
if (!isEnhanced) {
if (!dc.abstract) {
metaClass.constructor = { ->
getDomainInstance domainClass, ctx
}
}
metaClass.ident = {-> delegate[domainClass.identifier.name] }
metaClass.static.create = { ->
getDomainInstance domainClass, ctx
}
addValidationMethods(application, domainClass, ctx)
}
else {
AutowireCapableBeanFactory autowireCapableBeanFactory = ctx.autowireCapableBeanFactory
int byName = AutowireCapableBeanFactory.AUTOWIRE_BY_NAME
metaClass.static.autowireDomain = { instance ->
autowireCapableBeanFactory.autowireBeanProperties(instance, byName, false)
}
}
}
}
public static void addValidationMethods(GrailsApplication application, GrailsDomainClass dc, ApplicationContext ctx) {
def isEnhanced = dc.clazz.getAnnotation(Enhanced) != null
if(isEnhanced && ctx) {
if(!dc.abstract) {
def datastore = new SimpleMapDatastore(ctx.getBean("grailsDomainClassMappingContext", MappingContext), ctx as ConfigurableApplicationContext)
String validatorBeanName = "${dc.fullName}Validator"
Validator validator
if(ctx.containsBean(validatorBeanName)) {
validator = ctx.getBean(validatorBeanName, Validator)
} else {
validator = new GrailsDomainClassValidator()
validator.domainClass = dc
validator.grailsApplication = application
}
dc.clazz.setInstanceGormValidationApi(GormApiSupport.getGormValidationApi(datastore, dc.clazz, validator))
return
}
}
def metaClass = dc.metaClass
def domainClass = dc
metaClass.hasErrors = {-> delegate.errors?.hasErrors() }
def get
def put
try {
def rch = application.classLoader.loadClass("org.springframework.web.context.request.RequestContextHolder")
get = {
def attributes = rch.getRequestAttributes()
if (attributes) {
return attributes.request.getAttribute(it)
}
return PROPERTY_INSTANCE_MAP.get().get(it)
}
put = { key, val ->
def attributes = rch.getRequestAttributes()
if (attributes) {
attributes.request.setAttribute(key,val)
}
else {
PROPERTY_INSTANCE_MAP.get().put(key,val)
}
}
}
catch (Throwable e) {
get = { PROPERTY_INSTANCE_MAP.get().get(it) }
put = { key, val -> PROPERTY_INSTANCE_MAP.get().put(key,val) }
}
metaClass.getErrors = { ->
def errors
def key = "org.codehaus.groovy.grails.ERRORS_${delegate.class.name}_${System.identityHashCode(delegate)}"
errors = get(key)
if (!errors) {
errors = new ValidationErrors(delegate)
put key, errors
}
errors
}
metaClass.setErrors = { Errors errors ->
def key = "org.codehaus.groovy.grails.ERRORS_${delegate.class.name}_${System.identityHashCode(delegate)}"
put key, errors
}
metaClass.clearErrors = { ->
delegate.setErrors (new BeanPropertyBindingResult(delegate, delegate.getClass().getName()))
}
if (!domainClass.hasMetaMethod("validate")) {
metaClass.validate = { ->
DomainClassPluginSupport.validateInstance(delegate, ctx)
}
}
}
/**
* Registers the constraints property for the given MetaClass and domainClass instance
*/
static void registerConstraintsProperty(MetaClass metaClass, GrailsDomainClass domainClass) {
metaClass.static.getConstraints = { -> domainClass.constrainedProperties }
metaClass.getConstraints = {-> domainClass.constrainedProperties }
}
private static getDomainInstance(domainClass, ctx) {
def obj
if (ctx.containsBean(domainClass.fullName)) {
obj = ctx.getBean(domainClass.fullName)
}
else {
obj = BeanUtils.instantiateClass(domainClass.clazz)
}
obj
}
static addRelationshipManagementMethods(GrailsDomainClass dc, ApplicationContext ctx) {
def metaClass = dc.metaClass
for (p in dc.persistentProperties) {
def prop = p
if (prop.basicCollectionType) {
def collectionName = GrailsClassUtils.getClassNameRepresentation(prop.name)
metaClass."addTo$collectionName" = { obj ->
if (obj instanceof CharSequence && !(obj instanceof String)) {
obj = obj.toString()
}
if (prop.referencedPropertyType.isInstance(obj)) {
if (delegate[prop.name] == null) {
delegate[prop.name] = GrailsClassUtils.createConcreteCollection(prop.type)
}
delegate[prop.name] << obj
return delegate
}
else {
throw new MissingMethodException("addTo${collectionName}", dc.clazz, [obj] as Object[])
}
}
metaClass."removeFrom$collectionName" = { obj ->
if (delegate[prop.name]) {
if (obj instanceof CharSequence && !(obj instanceof String)) {
obj = obj.toString()
}
delegate[prop.name].remove(obj)
}
return delegate
}
}
else if (prop.oneToOne || prop.manyToOne) {
def identifierPropertyName = "${prop.name}Id"
if (!dc.hasMetaProperty(identifierPropertyName)) {
def getterName = GrailsClassUtils.getGetterName(identifierPropertyName)
metaClass."$getterName" = {-> GrailsDomainConfigurationUtil.getAssociationIdentifier(
delegate, prop.name, prop.referencedDomainClass) }
}
}
else if (prop.oneToMany || prop.manyToMany) {
if (metaClass instanceof ExpandoMetaClass) {
def propertyName = prop.name
def collectionName = GrailsClassUtils.getClassNameRepresentation(propertyName)
def otherDomainClass = prop.referencedDomainClass
metaClass."addTo${collectionName}" = { Object arg ->
Object obj
if (delegate[prop.name] == null) {
delegate[prop.name] = GrailsClassUtils.createConcreteCollection(prop.type)
}
if (arg instanceof Map) {
obj = getDomainInstance(otherDomainClass, ctx)
obj.properties = arg
delegate[prop.name].add(obj)
}
else if (otherDomainClass.clazz.isInstance(arg)) {
obj = arg
delegate[prop.name].add(obj)
}
else {
throw new MissingMethodException("addTo${collectionName}", dc.clazz, [arg] as Object[])
}
if (prop.bidirectional && prop.otherSide) {
def otherSide = prop.otherSide
if (otherSide.oneToMany || otherSide.manyToMany) {
String name = prop.otherSide.name
if (!obj[name]) {
obj[name] = GrailsClassUtils.createConcreteCollection(prop.otherSide.type)
}
obj[prop.otherSide.name].add(delegate)
}
else {
obj[prop.otherSide.name] = delegate
}
}
delegate
}
metaClass."removeFrom${collectionName}" = {Object arg ->
if (otherDomainClass.clazz.isInstance(arg)) {
delegate[prop.name]?.remove(arg)
if (prop.bidirectional) {
if (prop.manyToMany) {
String name = prop.otherSide.name
arg[name]?.remove(delegate)
}
else {
arg[prop.otherSide.name] = null
}
}
}
else {
throw new MissingMethodException("removeFrom${collectionName}", dc.clazz, [arg] as Object[])
}
delegate
}
}
}
}
}
}