EventListenerFactory.groovy
01 /*
02  * Copyright 2008-2016 the original author or authors.
03  *
04  * Licensed under the Apache License, Version 2.0 (the "License");
05  * you may not use this file except in compliance with the License.
06  * You may obtain a copy of the License at
07  *
08  *     http://www.apache.org/licenses/LICENSE-2.0
09  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package griffon.builder.pivot.factory
17 
18 /**
19  @author Andres Almiray
20  */
21 class EventListenerFactory extends AbstractFactory {
22     private static final Class[] PARAMS = [FactoryBuilderSupportas Class[]
23     final Class adapterClass
24     final List<Class> parents = []
25     final String getListenersMethod
26 
27     EventListenerFactory(Class adapterClass, List<Class> parents, String listenersMethod) {
28         this.adapterClass = adapterClass
29         this.parents.addAll(parents)
30         this.getListenersMethod = listenersMethod
31     }
32 
33     Object newInstance(FactoryBuilderSupport builder, Object name, Object value, Map attributes)
34     throws InstantiationException, IllegalAccessException {
35         if (value && adapterClass.isAssignableFrom(value.getClass())) return value
36         adapterClass.getDeclaredConstructor(PARAMS).newInstance([builderas Object[])
37     }
38 
39     boolean isHandlesNodeChildren() {
40         return true
41     }
42 
43     boolean onNodeChildren(FactoryBuilderSupport builder, Object node, Closure childContent) {
44         node.delegate = childContent.delegate
45         childContent.delegate = node
46         childContent()
47         return false
48     }
49 
50     void setParent(FactoryBuilderSupport builder, Object parent, Object node) {
51         if (!parentreturn
52         for (candidate in parents) {
53             if (candidate.isAssignableFrom(parent.getClass())) {
54                 parent."$getListenersMethod"().add(node)
55                 break
56             }
57         }
58     }
59 }