Merge "Add service reference binding to config registry."
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / dom / serializer / impl / TransformerGenerator.xtend
1 package org.opendaylight.controller.sal.binding.dom.serializer.impl
2
3 import javassist.ClassPool
4 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType
5 import org.opendaylight.yangtools.yang.model.api.SchemaNode
6 import org.opendaylight.controller.sal.binding.codegen.util.JavassistUtils
7 import javassist.CtClass
8 import java.util.Map
9 import org.opendaylight.yangtools.yang.common.QName
10 import javassist.CtField
11 import static javassist.Modifier.*
12 import static org.opendaylight.controller.sal.binding.dom.serializer.impl.CodecMapping.*
13 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode
14 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode
15 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer
16 import org.opendaylight.yangtools.sal.binding.model.api.Type
17 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder
18 import org.opendaylight.yangtools.binding.generator.util.Types
19 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType
20 import java.util.HashMap
21 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode
22 import org.opendaylight.yangtools.binding.generator.util.BindingGeneratorUtil
23 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode
24 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode
25 import java.util.List
26 import java.util.TreeSet
27 import com.google.common.base.Joiner
28 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedTransferObject
29 import org.opendaylight.yangtools.sal.binding.model.api.Enumeration
30 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode
31 import static org.opendaylight.controller.sal.binding.impl.util.ClassLoaderUtils.*;
32 import org.opendaylight.yangtools.yang.binding.BindingDeserializer
33 import org.opendaylight.yangtools.yang.binding.BindingCodec
34 import org.slf4j.LoggerFactory
35 import org.opendaylight.controller.sal.binding.codegen.CodeGenerationException
36 import org.opendaylight.yangtools.yang.model.api.ChoiceNode
37 import java.security.ProtectionDomain
38 import java.io.File
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier
40 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedProperty
41 import java.util.Map.Entry
42 import java.util.AbstractMap.SimpleEntry
43 import org.opendaylight.yangtools.yang.binding.DataObject
44 import org.opendaylight.yangtools.yang.binding.Augmentation
45 import java.util.Iterator
46 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema
47 import java.util.concurrent.ConcurrentHashMap
48 import static extension org.opendaylight.controller.sal.binding.impl.util.YangSchemaUtils.*;
49 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl
50 import org.opendaylight.yangtools.yang.model.util.ExtendedType
51 import org.opendaylight.yangtools.yang.model.util.EnumerationType
52 import static com.google.common.base.Preconditions.*
53 import org.opendaylight.yangtools.yang.model.api.SchemaPath
54 import javassist.CtMethod
55 import javassist.CannotCompileException
56 import java.util.concurrent.locks.Lock
57 import java.util.concurrent.Callable
58 import org.opendaylight.controller.sal.binding.impl.util.ClassLoaderUtils
59
60 class TransformerGenerator {
61
62     private static val log = LoggerFactory.getLogger(TransformerGenerator)
63
64     public static val STRING = Types.typeForClass(String);
65     public static val BOOLEAN = Types.typeForClass(Boolean);
66     public static val INTEGER = Types.typeForClass(Integer);
67     public static val INSTANCE_IDENTIFIER = Types.typeForClass(InstanceIdentifier)
68
69     //public static val DECIMAL = Types.typeForClass(Decimal);
70     public static val LONG = Types.typeForClass(Long);
71
72     val ClassPool classPool
73     val extension JavassistUtils utils;
74
75     CtClass BINDING_CODEC
76
77     CtClass ctQName
78
79     @Property
80     var File classFileCapturePath;
81
82     @Property
83     var Map<Type, Type> typeDefinitions = new ConcurrentHashMap();
84
85     @Property
86     var Map<Type, GeneratedTypeBuilder> typeToDefinition = new ConcurrentHashMap();
87
88     @Property
89     var Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap();
90
91     @Property
92     var Map<Type, SchemaNode> typeToSchemaNode = new ConcurrentHashMap();
93
94     @Property
95     var Map<Type, AugmentationSchema> typeToAugmentation = new ConcurrentHashMap();
96
97     @Property
98     var GeneratorListener listener;
99
100     public static val CLASS_TYPE = Types.typeForClass(Class);
101
102     public new(ClassPool pool) {
103         classPool = pool;
104         utils = new JavassistUtils(pool)
105
106         BINDING_CODEC = BindingCodec.asCtClass;
107         ctQName = QName.asCtClass
108     }
109
110     def Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerFor(Class<?> inputType) {
111         return withClassLoaderAndLock(inputType.classLoader, lock) [ |
112             val ret = getGeneratedClass(inputType)
113             if (ret !== null) {
114                 listener.onClassProcessed(inputType);
115                 return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
116             }
117             val ref = Types.typeForClass(inputType)
118             val node = typeToSchemaNode.get(ref)
119             val typeSpecBuilder = typeToDefinition.get(ref)
120             checkState(typeSpecBuilder !== null, "Could not find typedefinition for %s", inputType.name);
121             val typeSpec = typeSpecBuilder.toInstance();
122             val newret = generateTransformerFor(inputType, typeSpec, node);
123             listener.onClassProcessed(inputType);
124             return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
125         ]
126     }
127
128     def Class<? extends BindingCodec<Map<QName, Object>, Object>> transformerFor(Class<?> inputType, DataSchemaNode node) {
129         return withClassLoaderAndLock(inputType.classLoader, lock) [ |
130             val ret = getGeneratedClass(inputType)
131             if (ret !== null) {
132                 listener.onClassProcessed(inputType);
133                 return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
134             }
135             val ref = Types.typeForClass(inputType)
136             var typeSpecBuilder = typeToDefinition.get(ref)
137             if (typeSpecBuilder == null) {
138                 typeSpecBuilder = pathToType.get(node.path);
139             }
140             checkState(typeSpecBuilder !== null, "Could not find TypeDefinition for %s, $s", inputType.name, node);
141             val typeSpec = typeSpecBuilder.toInstance();
142             val newret = generateTransformerFor(inputType, typeSpec, node);
143             listener.onClassProcessed(inputType);
144             return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
145         ]
146     }
147
148     def Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentationTransformerFor(Class<?> inputType) {
149         return withClassLoaderAndLock(inputType.classLoader, lock) [ |
150             val ret = getGeneratedClass(inputType)
151             if (ret !== null) {
152                 return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
153             }
154             val ref = Types.typeForClass(inputType)
155             val node = typeToAugmentation.get(ref)
156             val typeSpecBuilder = typeToDefinition.get(ref)
157             val typeSpec = typeSpecBuilder.toInstance();
158             val newret = generateAugmentationTransformerFor(inputType, typeSpec, node);
159             listener.onClassProcessed(inputType);
160             return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
161         ]
162     }
163
164     def Class<? extends BindingCodec<Object, Object>> caseCodecFor(Class<?> inputType, ChoiceCaseNode node) {
165         return withClassLoaderAndLock(inputType.classLoader, lock) [ |
166             val ret = getGeneratedClass(inputType)
167             if (ret !== null) {
168                 return ret as Class<? extends BindingCodec<Object, Object>>;
169             }
170             val ref = Types.typeForClass(inputType)
171             val typeSpecBuilder = typeToDefinition.get(ref)
172             val typeSpec = typeSpecBuilder.toInstance();
173             val newret = generateCaseCodec(inputType, typeSpec, node);
174             return newret as Class<? extends BindingCodec<Object, Object>>;
175         ]
176     }
177
178     def Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifiable(Class<?> parentType) {
179         return withClassLoaderAndLock(parentType.classLoader, lock) [ |
180             val inputName = parentType.name + "Key";
181             val inputType = loadClassWithTCCL(inputName);
182             val ret = getGeneratedClass(inputType)
183             if (ret !== null) {
184                 return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
185             }
186             val ref = Types.typeForClass(parentType)
187             val node = typeToSchemaNode.get(ref) as ListSchemaNode
188             val typeSpecBuilder = typeToDefinition.get(ref)
189             val typeSpec = typeSpecBuilder.identifierDefinition;
190             val newret = generateKeyTransformerFor(inputType, typeSpec, node);
191             return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
192         ]
193     }
194
195     def getIdentifierDefinition(GeneratedTypeBuilder builder) {
196         val inst = builder.toInstance
197         val keyMethod = inst.methodDefinitions.findFirst[name == "getKey"]
198         return keyMethod.returnType as GeneratedTransferObject
199     }
200
201     def Class<? extends BindingCodec<Map<QName, Object>, Object>> keyTransformerForIdentifier(Class<?> inputType) {
202         return withClassLoaderAndLock(inputType.classLoader, lock) [ |
203             val ret = getGeneratedClass(inputType)
204             if (ret !== null) {
205                 return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
206             }
207             val ref = Types.typeForClass(inputType)
208             val node = typeToSchemaNode.get(ref) as ListSchemaNode
209             val typeSpecBuilder = typeToDefinition.get(ref)
210             val typeSpec = typeSpecBuilder.toInstance();
211             val newret = generateKeyTransformerFor(inputType, typeSpec, node);
212             return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
213         ]
214     }
215
216     private def Class<?> keyTransformerFor(Class<?> inputType, GeneratedType type, ListSchemaNode schema) {
217         return withClassLoaderAndLock(inputType.classLoader, lock) [ |
218             val transformer = getGeneratedClass(inputType)
219             if (transformer != null) {
220                 return transformer;
221             }
222             val newret = generateKeyTransformerFor(inputType, type, schema);
223             return newret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
224         ]
225     }
226
227     private def Class<?> getGeneratedClass(Class<? extends Object> cls) {
228
229         try {
230             return loadClassWithTCCL(cls.codecClassName)
231         } catch (ClassNotFoundException e) {
232             return null;
233         }
234     }
235
236     private def Class<?> keyTransformer(GeneratedType type, ListSchemaNode node) {
237         val cls = loadClassWithTCCL(type.resolvedName + "Key");
238         keyTransformerFor(cls, type, node);
239     }
240
241     private def serializer(Type type, DataSchemaNode node) {
242         val cls = loadClassWithTCCL(type.resolvedName);
243         transformerFor(cls, node);
244     }
245
246     private def Class<?> getValueSerializer(GeneratedTransferObject type) {
247         val cls = loadClassWithTCCL(type.resolvedName);
248         val transformer = cls.generatedClass;
249         if (transformer !== null) {
250             return transformer;
251         }
252         return withClassLoaderAndLock(cls.classLoader, lock) [ |
253             val valueTransformer = generateValueTransformer(cls, type);
254             return valueTransformer;
255         ]
256     }
257
258     private def Class<?> getValueSerializer(Enumeration type) {
259         val cls = loadClassWithTCCL(type.resolvedName);
260         val transformer = cls.generatedClass;
261         if (transformer !== null) {
262             return transformer;
263         }
264
265         return withClassLoaderAndLock(cls.classLoader, lock) [ |
266             val valueTransformer = generateValueTransformer(cls, type);
267             return valueTransformer;
268         ]
269     }
270
271     private def generateKeyTransformerFor(Class<? extends Object> inputType, GeneratedType typeSpec, ListSchemaNode node) {
272         try {
273
274             //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
275             val properties = typeSpec.allProperties;
276             val ctCls = createClass(inputType.codecClassName) [
277                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
278                 staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
279                 staticField(it, IDENTITYREF_CODEC, BindingCodec)
280                 staticQNameField(node.QName);
281                 implementsType(BINDING_CODEC)
282                 method(Object, "toDomStatic", QName, Object) [
283                     modifiers = PUBLIC + FINAL + STATIC
284                     bodyChecked = '''
285                         {
286                             «QName.name» _resultName;
287                             if($1 != null) {
288                                 _resultName = «QName.name».create($1,QNAME.getLocalName());
289                             } else {
290                                 _resultName = QNAME;
291                             }
292                             java.util.List _childNodes = new java.util.ArrayList();
293                             «inputType.resolvedName» value = («inputType.name») $2;
294                             «FOR key : node.keyDefinition»
295                                 «val propertyName = key.getterName»
296                                 «val keyDef = node.getDataChildByName(key)»
297                                 «val property = properties.get(propertyName)»
298                                 «serializeProperty(keyDef, property, propertyName)»;
299                             «ENDFOR»
300                             return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
301                         }
302                     '''
303                 ]
304                 method(Object, "fromDomStatic", QName, Object) [
305                     modifiers = PUBLIC + FINAL + STATIC
306                     bodyChecked = '''
307                         {
308                             if($2 == null){
309                                 return  null;
310                             }
311                             «QName.name» _localQName = $1;
312                             java.util.Map _compositeNode = (java.util.Map) $2;
313                             boolean _is_empty = true;
314                             «FOR key : node.keyDefinition»
315                                 «val propertyName = key.getterName»
316                                 «val keyDef = node.getDataChildByName(key)»
317                                 «val property = properties.get(propertyName)»
318                                 «deserializeProperty(keyDef, property, propertyName)»;
319                             «ENDFOR»
320                             «inputType.resolvedName» _value = new «inputType.name»(«node.keyDefinition.
321                             keyConstructorList»);
322                             return _value;
323                         }
324                     '''
325                 ]
326                 method(Object, "serialize", Object) [
327                     bodyChecked = '''
328                         {
329                             java.util.Map.Entry _input =  (java.util.Map.Entry) $1;
330                             «QName.name» _localQName = («QName.name») _input.getKey();
331                             «inputType.name» _keyValue = («inputType.name») _input.getValue();
332                             return toDomStatic(_localQName,_keyValue);
333                         }
334                     '''
335                 ]
336                 method(Object, "deserialize", Object) [
337                     bodyChecked = '''
338                         return fromDomStatic(QNAME,$1);
339                     '''
340                 ]
341             ]
342             val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
343             log.info("DOM Codec for {} was generated {}", inputType, ret)
344             return ret as Class<? extends BindingCodec<Map<QName,Object>, ?>>;
345         } catch (Exception e) {
346             processException(inputType, e);
347             return null;
348         }
349     }
350
351     private def Class<? extends BindingCodec<Object, Object>> generateCaseCodec(Class<?> inputType, GeneratedType type,
352         ChoiceCaseNode node) {
353         try {
354
355             //log.info("Generating DOM Codec for {} with {}, TCCL is: {}", inputType, inputType.classLoader,Thread.currentThread.contextClassLoader)
356             val ctCls = createClass(type.codecClassName) [
357                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
358                 implementsType(BINDING_CODEC)
359                 staticQNameField(node.QName);
360                 staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
361                 staticField(it, AUGMENTATION_CODEC, BindingCodec)
362                 staticField(it, IDENTITYREF_CODEC, BindingCodec)
363                 method(Object, "toDomStatic", QName, Object) [
364                     modifiers = PUBLIC + FINAL + STATIC
365                     bodyChecked = '''
366                         {
367                             «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
368                             java.util.List _childNodes = new java.util.ArrayList();
369                             «type.resolvedName» value = («type.resolvedName») $2;
370                             «transformDataContainerBody(type, type.allProperties, node)»
371                             return ($r) _childNodes;
372                         }
373                     '''
374                 ]
375                 method(Object, "serialize", Object) [
376                     bodyChecked = '''
377                         {
378                             java.util.Map.Entry _input = (java.util.Map.Entry) $1;
379                             «QName.name» _localName = QNAME;
380                             if(_input.getKey() != null) {
381                                 _localName = («QName.name») _input.getKey();
382                             }
383                             return toDomStatic(_localName,_input.getValue());
384                         }
385                     '''
386                 ]
387                 method(Object, "fromDomStatic", QName, Object) [
388                     modifiers = PUBLIC + FINAL + STATIC
389                     bodyChecked = deserializeBody(type, node)
390                 ]
391                 method(Object, "deserialize", Object) [
392                     bodyChecked = '''
393                         {
394                             //System.out.println("«type.name»#deserialize: " +$1);
395                             java.util.Map.Entry _input = (java.util.Map.Entry) $1;
396                             return fromDomStatic((«QName.name»)_input.getKey(),_input.getValue());
397                         }
398                     '''
399                 ]
400             ]
401
402             val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)  as Class<? extends BindingCodec<Object, Object>>
403             listener?.onDataContainerCodecCreated(inputType, ret);
404             log.info("DOM Codec for {} was generated {}", inputType, ret)
405             return ret;
406         } catch (Exception e) {
407             processException(inputType, e);
408             return null;
409         }
410     }
411
412     private def dispatch  Class<? extends BindingCodec<Map<QName, Object>, Object>> generateTransformerFor(
413         Class<?> inputType, GeneratedType typeSpec, SchemaNode node) {
414         try {
415
416             //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
417             val ctCls = createClass(typeSpec.codecClassName) [
418                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
419                 staticQNameField(node.QName);
420                 staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
421                 staticField(it, IDENTITYREF_CODEC, BindingCodec)
422                 staticField(it, AUGMENTATION_CODEC, BindingCodec)
423                 implementsType(BINDING_CODEC)
424                 method(Object, "toDomStatic", QName, Object) [
425                     modifiers = PUBLIC + FINAL + STATIC
426                     bodyChecked = serializeBodyFacade(typeSpec, node)
427                 ]
428                 method(Object, "serialize", Object) [
429                     bodyChecked = '''
430                         {
431                             java.util.Map.Entry _input = (java.util.Map.Entry) $1;
432                             «QName.name» _localName = QNAME;
433                             if(_input.getKey() != null) {
434                                 _localName = («QName.name») _input.getKey();
435                             }
436                             return toDomStatic(_localName,_input.getValue());
437                         }
438                     '''
439                 ]
440                 method(Object, "fromDomStatic", QName, Object) [
441                     modifiers = PUBLIC + FINAL + STATIC
442                     bodyChecked = deserializeBody(typeSpec, node)
443                 ]
444                 method(Object, "deserialize", Object) [
445                     bodyChecked = '''
446                         return fromDomStatic(QNAME,$1);
447                     '''
448                 ]
449             ]
450
451             val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Map<QName,Object>, Object>>
452             listener?.onDataContainerCodecCreated(inputType, ret);
453             log.info("DOM Codec for {} was generated {}", inputType, ret)
454             return ret;
455         } catch (Exception e) {
456             processException(inputType, e);
457             return null;
458         }
459     }
460
461     private def Class<? extends BindingCodec<Map<QName, Object>, Object>> generateAugmentationTransformerFor(
462         Class<?> inputType, GeneratedType type, AugmentationSchema node) {
463         try {
464
465             //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
466             val properties = type.allProperties
467             val ctCls = createClass(type.codecClassName) [
468                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
469                 staticQNameField(node.augmentationQName);
470                 staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
471                 staticField(it, AUGMENTATION_CODEC, BindingCodec)
472                 staticField(it, IDENTITYREF_CODEC, BindingCodec)
473                 implementsType(BINDING_CODEC)
474                 method(Object, "toDomStatic", QName, Object) [
475                     modifiers = PUBLIC + FINAL + STATIC
476                     bodyChecked = '''
477                         {
478                             //System.out.println("Qname " + $1);
479                             //System.out.println("Value " + $2);
480                             «QName.name» _resultName = «QName.name».create(QNAME,QNAME.getLocalName());
481                             java.util.List _childNodes = new java.util.ArrayList();
482                             «type.resolvedName» value = («type.resolvedName») $2;
483                             «FOR child : node.childNodes»
484                                 «var signature = properties.getFor(child)»
485                                 //System.out.println("«signature.key»" + value.«signature.key»());
486                                 «serializeProperty(child, signature.value, signature.key)»
487                             «ENDFOR»
488                             return ($r) _childNodes;
489                         }
490                     '''
491                 ]
492                 method(Object, "serialize", Object) [
493                     bodyChecked = '''
494                         {
495                         java.util.Map.Entry _input = (java.util.Map.Entry) $1;
496                         «QName.name» _localName = QNAME;
497                         if(_input.getKey() != null) {
498                             _localName = («QName.name») _input.getKey();
499                         }
500                         return toDomStatic(_localName,_input.getValue());
501                         }
502                     '''
503                 ]
504                 method(Object, "fromDomStatic", QName, Object) [
505                     modifiers = PUBLIC + FINAL + STATIC
506                     bodyChecked = '''
507                         {
508                             «QName.name» _localQName = QNAME;
509                             
510                             if($2 == null) {
511                             return null;
512                             }
513                             java.util.Map _compositeNode = (java.util.Map) $2;
514                             //System.out.println(_localQName + " " + _compositeNode);
515                             «type.builderName» _builder = new «type.builderName»();
516                             boolean _is_empty = true;
517                             «FOR child : node.childNodes»
518                                 «val signature = properties.getFor(child)»
519                                 «deserializeProperty(child, signature.value, signature.key)»
520                                 _builder.«signature.key.toSetter»(«signature.key»);
521                             «ENDFOR»
522                             if(_is_empty) {
523                                 return null;
524                             }
525                             return _builder.build();
526                         }
527                     '''
528                 ]
529                 method(Object, "deserialize", Object) [
530                     bodyChecked = '''
531                         return fromDomStatic(QNAME,$1);
532                     '''
533                 ]
534             ]
535
536             val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain) as Class<? extends BindingCodec<Map<QName,Object>, Object>>
537             listener?.onDataContainerCodecCreated(inputType, ret);
538             return ret;
539         } catch (Exception e) {
540             processException(inputType, e);
541             return null;
542         }
543     }
544
545     private def dispatch  Class<? extends BindingCodec<Map<QName, Object>, Object>> generateTransformerFor(
546         Class<?> inputType, GeneratedType typeSpec, ChoiceNode node) {
547         try {
548
549             //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
550             val ctCls = createClass(typeSpec.codecClassName) [
551                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
552                 //staticQNameField(inputType);
553                 staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
554                 staticField(it, IDENTITYREF_CODEC, BindingCodec)
555                 staticField(it, CLASS_TO_CASE_MAP, Map)
556                 staticField(it, COMPOSITE_TO_CASE, Map)
557                 //staticField(it,QNAME_TO_CASE_MAP,BindingCodec)
558                 implementsType(BINDING_CODEC)
559                 method(List, "toDomStatic", QName, Object) [
560                     modifiers = PUBLIC + FINAL + STATIC
561                     bodyChecked = '''
562                         {
563                             if($2 == null) {
564                                 return null;
565                             }
566                             «DataObject.name» _baValue = («DataObject.name») $2;
567                             Class _baClass = _baValue.getImplementedInterface();
568                             «BINDING_CODEC.name» _codec =  «CLASS_TO_CASE_MAP».get(_baClass);
569                             if(_codec == null) {
570                                 return null;
571                             }
572                             java.util.Map.Entry _input = new «SimpleEntry.name»($1,_baValue);
573                             Object _ret =  _codec.serialize(_input);
574                             //System.out.println("«typeSpec.name»#toDomStatic: " + _ret);
575                             return («List.name») _ret;
576                         }
577                     '''
578                 ]
579                 method(Object, "serialize", Object) [
580                     bodyChecked = '''
581                         throw new «UnsupportedOperationException.name»("Direct invocation not supported.");
582                     '''
583                 ]
584                 method(Object, "fromDomStatic", QName, Map) [
585                     modifiers = PUBLIC + FINAL + STATIC
586                     bodyChecked = '''
587                         {
588                             «BINDING_CODEC.name» _codec = («BINDING_CODEC.name») «COMPOSITE_TO_CASE».get($2);
589                             if(_codec != null) {
590                                 return _codec.deserialize(new «SimpleEntry.name»($1,$2));
591                             }
592                             return null;
593                         }
594                     '''
595                 ]
596                 method(Object, "deserialize", Object) [
597                     bodyChecked = '''
598                         throw new «UnsupportedOperationException.name»("Direct invocation not supported.");
599                     '''
600                 ]
601             ]
602
603             val rawRet = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
604             val ret = rawRet as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
605             listener?.onChoiceCodecCreated(inputType, ret, node);
606             log.info("DOM Codec for {} was generated {}", inputType, ret)
607             return ret;
608         } catch (Exception e) {
609             processException(inputType, e);
610             return null;
611         }
612     }
613
614     private def keyConstructorList(List<QName> qnames) {
615         val names = new TreeSet<String>()
616         for (name : qnames) {
617             val fieldName = name.getterName;
618             names.add(fieldName);
619         }
620         return Joiner.on(",").join(names);
621     }
622
623     private def serializeBodyFacade(GeneratedType type, SchemaNode node) {
624         val ret = serializeBody(type, node);
625         return ret;
626     }
627
628     private def String deserializeBody(GeneratedType type, SchemaNode node) {
629         val ret = deserializeBodyImpl(type, node);
630         return ret;
631     }
632
633     private def deserializeKey(GeneratedType type, ListSchemaNode node) {
634         if (node.keyDefinition != null && !node.keyDefinition.empty) {
635             return '''
636                 «type.resolvedName»Key getKey = («type.resolvedName»Key) «keyTransformer(type, node).canonicalName».fromDomStatic(_localQName,_compositeNode);
637                 _builder.setKey(getKey);
638             ''';
639         }
640     }
641
642     private def dispatch String deserializeBodyImpl(GeneratedType type, SchemaNode node) '''
643         {
644             «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
645             
646             if($2 == null) {
647                 return null;
648             }
649             java.util.Map _compositeNode = (java.util.Map) $2;
650             «type.builderName» _builder = new «type.builderName»();
651             return _builder.build();
652         }
653     '''
654
655     private def dispatch String deserializeBodyImpl(GeneratedType type, ListSchemaNode node) '''
656         {
657             «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
658             if($2 == null) {
659                 return null;
660             }
661             java.util.Map _compositeNode = (java.util.Map) $2;
662             «type.builderName» _builder = new «type.builderName»();
663             «deserializeKey(type, node)»
664             «deserializeDataNodeContainerBody(type, node)»
665             «deserializeAugmentations»
666             return _builder.build();
667         }
668     '''
669
670     private def dispatch String deserializeBodyImpl(GeneratedType type, ContainerSchemaNode node) '''
671         {
672             «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
673             if($2 == null) {
674                 return null;
675             }
676             java.util.Map _compositeNode = (java.util.Map) $2;
677             «type.builderName» _builder = new «type.builderName»();
678             «deserializeDataNodeContainerBody(type, node)»
679             «deserializeAugmentations»
680             return _builder.build();
681         }
682     '''
683
684     private def dispatch String deserializeBodyImpl(GeneratedType type, ChoiceCaseNode node) '''
685         {
686             «QName.name» _localQName = «QName.name».create($1,QNAME.getLocalName());
687             
688             if($2 == null) {
689                 return null;
690             }
691             java.util.Map _compositeNode = (java.util.Map) $2;
692             //System.out.println(_localQName + " " + _compositeNode);
693             «type.builderName» _builder = new «type.builderName»();
694             «deserializeDataNodeContainerBody(type, node)»
695             «deserializeAugmentations»
696             return _builder.build();
697         }
698     '''
699
700     private def deserializeDataNodeContainerBody(GeneratedType type, DataNodeContainer node) {
701         deserializeNodeContainerBodyImpl(type, type.allProperties, node);
702     }
703
704     private def deserializeNodeContainerBodyImpl(GeneratedType type, HashMap<String, Type> properties,
705         DataNodeContainer node) {
706         val ret = '''
707             boolean _is_empty = true;
708             «FOR child : node.childNodes»
709                 «val signature = properties.getFor(child)»
710                 «IF signature !== null»
711                     «deserializeProperty(child, signature.value, signature.key)»
712                     _builder.«signature.key.toSetter»(«signature.key»);
713                 «ENDIF»
714             «ENDFOR»
715         '''
716         return ret;
717     }
718
719     def deserializeAugmentations() '''
720         java.util.Map _augmentation = (java.util.Map) «AUGMENTATION_CODEC».deserialize(_compositeNode);
721         if(_augmentation != null) {
722             «Iterator.name» _entries = _augmentation.entrySet().iterator();
723             while(_entries.hasNext()) {
724                 java.util.Map.Entry _entry = (java.util.Map.Entry) _entries.next();
725                 //System.out.println("Aug. key:" + _entry.getKey());
726                 Class _type = (Class) _entry.getKey();
727                 «Augmentation.resolvedName» _value = («Augmentation.name») _entry.getValue();
728                 if(_value != null) {
729                     _builder.addAugmentation(_type,_value);
730                 }
731             }
732         }
733     '''
734
735     private def dispatch CharSequence deserializeProperty(ListSchemaNode schema, ParameterizedType type,
736         String propertyName) '''
737         java.util.List _dom_«propertyName» = _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.
738             localName»"));
739         //System.out.println("«propertyName»#deCode"+_dom_«propertyName»);
740         java.util.List «propertyName» = new java.util.ArrayList();
741         if(_dom_«propertyName» != null) {
742             java.util.List _serialized = new java.util.ArrayList();
743             java.util.Iterator _iterator = _dom_«propertyName».iterator();
744             boolean _hasNext = _iterator.hasNext();
745             while(_hasNext) {
746                 Object _listItem = _iterator.next();
747                 _is_empty = false;
748                 //System.out.println("  item" + _listItem);
749                 Object _value = «type.actualTypeArguments.get(0).serializer(schema).resolvedName».fromDomStatic(_localQName,_listItem);
750                 //System.out.println("  value" + _value);
751                 «propertyName».add(_value);
752                 _hasNext = _iterator.hasNext();
753             }
754         }
755         
756         //System.out.println(" list" + «propertyName»);
757     '''
758
759     private def dispatch CharSequence deserializeProperty(LeafListSchemaNode schema, ParameterizedType type,
760         String propertyName) '''
761         java.util.List _dom_«propertyName» = _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.
762             localName»"));
763         java.util.List «propertyName» = new java.util.ArrayList();
764         if(_dom_«propertyName» != null) {
765             java.util.List _serialized = new java.util.ArrayList();
766             java.util.Iterator _iterator = _dom_«propertyName».iterator();
767             boolean _hasNext = _iterator.hasNext();
768             while(_hasNext) {
769                 _is_empty = false;
770                 Object _listItem = _iterator.next();
771                 if(_listItem instanceof java.util.Map.Entry) {
772                     Object _innerValue = ((java.util.Map.Entry) _listItem).getValue();
773                     Object _value = «deserializeValue(type.actualTypeArguments.get(0), "_innerValue")»;
774                     «propertyName».add(_value);
775                 }
776                 _hasNext = _iterator.hasNext();
777             }
778         }
779     '''
780
781     private def dispatch CharSequence deserializeProperty(LeafSchemaNode schema, Type type, String propertyName) '''
782         java.util.List _dom_«propertyName»_list = 
783             _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.localName»"));
784         «type.resolvedName» «propertyName» = null;
785         if(_dom_«propertyName»_list != null && _dom_«propertyName»_list.size() > 0) {
786             _is_empty = false;
787             java.util.Map.Entry _dom_«propertyName» = (java.util.Map.Entry) _dom_«propertyName»_list.get(0);
788             Object _inner_value = _dom_«propertyName».getValue();
789             «propertyName» = «deserializeValue(type, "_inner_value")»;
790         }
791     '''
792
793     private def dispatch CharSequence deserializeProperty(ContainerSchemaNode schema, Type type,
794         String propertyName) '''
795         java.util.List _dom_«propertyName»_list = 
796             _compositeNode.get(«QName.name».create(_localQName,"«schema.QName.localName»"));
797         «type.resolvedName» «propertyName» = null;
798         if(_dom_«propertyName»_list != null && _dom_«propertyName»_list.size() > 0) {
799             _is_empty = false;
800             java.util.Map _dom_«propertyName» = (java.util.Map) _dom_«propertyName»_list.get(0);
801             «propertyName» =  «type.serializer(schema).resolvedName».fromDomStatic(_localQName,_dom_«propertyName»);
802         }
803     '''
804
805     private def dispatch CharSequence deserializeProperty(ChoiceNode schema, Type type, String propertyName) '''
806         «type.resolvedName» «propertyName» = «type.serializer(schema).resolvedName».fromDomStatic(_localQName,_compositeNode);
807         if(«propertyName» != null) {
808             _is_empty = false;
809         }
810     '''
811
812     private def dispatch String deserializeValue(GeneratedTransferObject type, String domParameter) '''
813         («type.resolvedName») «type.valueSerializer.resolvedName».fromDomValue(«domParameter»)
814     '''
815
816     private def dispatch String deserializeValue(Enumeration type, String domParameter) '''
817         («type.resolvedName») «type.valueSerializer.resolvedName».fromDomValue(«domParameter»)
818     '''
819
820     private def dispatch Class<? extends BindingCodec<Map<QName, Object>, Object>> generateValueTransformer(
821         Class<?> inputType, GeneratedTransferObject typeSpec) {
822         try {
823
824             val returnType = typeSpec.valueReturnType;
825             if (returnType == null) {
826                 val ctCls = createDummyImplementation(inputType, typeSpec);
827                 val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
828                 return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
829             }
830
831             val ctCls = createClass(typeSpec.codecClassName) [
832                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
833                 if (inputType.isYangBindingAvailable) {
834                     implementsType(BINDING_CODEC)
835                     staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
836                     staticField(it, IDENTITYREF_CODEC, BindingCodec)
837                     implementsType(BindingDeserializer.asCtClass)
838                 }
839                 method(Object, "toDomValue", Object) [
840                     modifiers = PUBLIC + FINAL + STATIC
841                     val ctSpec = typeSpec.asCtClass;
842                     bodyChecked = '''
843                         {
844                             //System.out.println("«inputType.simpleName»#toDomValue: "+$1);
845                             
846                             if($1 == null) {
847                                 return null;
848                             }
849                             «typeSpec.resolvedName» _encapsulatedValue = («typeSpec.resolvedName») $1;
850                             //System.out.println("«inputType.simpleName»#toDomValue:Enc: "+_encapsulatedValue);
851                             «returnType.resolvedName» _value =  _encapsulatedValue.getValue();
852                             //System.out.println("«inputType.simpleName»#toDomValue:DeEnc: "+_value);
853                             Object _domValue = «serializeValue(returnType, "_value")»;
854                             return _domValue;
855                         }
856                     '''
857                 ]
858                 method(Object, "serialize", Object) [
859                     bodyChecked = '''
860                         {
861                             return toDomValue($1);
862                         }
863                     '''
864                 ]
865                 method(Object, "fromDomValue", Object) [
866                     modifiers = PUBLIC + FINAL + STATIC
867                     bodyChecked = '''
868                         {
869                             //System.out.println("«inputType.simpleName»#fromDomValue: "+$1);
870                             
871                             if($1 == null) {
872                                 return null;
873                             }
874                             «returnType.resolvedName» _simpleValue = «deserializeValue(returnType, "$1")»;
875                             «typeSpec.resolvedName» _value = new «typeSpec.resolvedName»(_simpleValue);
876                             return _value;
877                         }
878                     '''
879                 ]
880                 method(Object, "deserialize", Object) [
881                     bodyChecked = '''{
882                             return fromDomValue($1);
883                     }
884                     '''
885                 ]
886             ]
887
888             val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
889             log.info("DOM Codec for {} was generated {}", inputType, ret)
890             return ret as Class<? extends BindingCodec<Map<QName,Object>, Object>>;
891         } catch (Exception e) {
892             log.error("Cannot compile DOM Codec for {}", inputType, e);
893             val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
894             exception.addSuppressed(e);
895             throw exception;
896         }
897
898     }
899
900     def boolean isYangBindingAvailable(Class<?> class1) {
901         try {
902             val bindingCodecClass = class1.classLoader.loadClass(BINDING_CODEC.name);
903             return bindingCodecClass !== null;
904         } catch (ClassNotFoundException e) {
905             return false;
906         }
907     }
908
909     private def createDummyImplementation(Class<?> object, GeneratedTransferObject typeSpec) {
910         log.info("Generating Dummy DOM Codec for {} with {}", object, object.classLoader)
911         return createClass(typeSpec.codecClassName) [
912             if (object.isYangBindingAvailable) {
913                 implementsType(BINDING_CODEC)
914                 staticField(it, INSTANCE_IDENTIFIER_CODEC, BindingCodec)
915                 staticField(it, IDENTITYREF_CODEC, BindingCodec)
916                 implementsType(BindingDeserializer.asCtClass)
917             }
918             //implementsType(BindingDeserializer.asCtClass)
919             method(Object, "toDomValue", Object) [
920                 modifiers = PUBLIC + FINAL + STATIC
921                 bodyChecked = '''{
922                     if($1 == null) {
923                         return null;
924                     }
925                     return $1.toString();
926                     
927                     }'''
928             ]
929             method(Object, "serialize", Object) [
930                 bodyChecked = '''
931                     {
932                         return toDomValue($1);
933                     }
934                 '''
935             ]
936             method(Object, "fromDomValue", Object) [
937                 modifiers = PUBLIC + FINAL + STATIC
938                 bodyChecked = '''return null;'''
939             ]
940             method(Object, "deserialize", Object) [
941                 bodyChecked = '''{
942                         return fromDomValue($1);
943                     }
944                     '''
945             ]
946         ]
947     }
948
949     private def Type getValueReturnType(GeneratedTransferObject object) {
950         for (prop : object.properties) {
951             if (prop.name == "value") {
952                 return prop.returnType;
953             }
954         }
955         if (object.superType != null) {
956             return getValueReturnType(object.superType);
957         }
958         return null;
959     }
960
961     private def dispatch Class<?> generateValueTransformer(Class<?> inputType, Enumeration typeSpec) {
962         try {
963             val typeRef = new ReferencedTypeImpl(typeSpec.packageName, typeSpec.name);
964             val schema = typeToSchemaNode.get(typeRef) as ExtendedType;
965             val enumSchema = schema.baseType as EnumerationType;
966
967             //log.info("Generating DOM Codec for {} with {}", inputType, inputType.classLoader)
968             val ctCls = createClass(typeSpec.codecClassName) [
969                 //staticField(Map,"AUGMENTATION_SERIALIZERS");
970                 //implementsType(BINDING_CODEC)
971                 method(Object, "toDomValue", Object) [
972                     modifiers = PUBLIC + FINAL + STATIC
973                     bodyChecked = '''{
974                             if($1 == null) {
975                                 return null;
976                             }
977                             «typeSpec.resolvedName» _value = («typeSpec.resolvedName») $1;
978                             «FOR en : enumSchema.values»
979                             if(«typeSpec.resolvedName».«BindingGeneratorUtil.parseToClassName(en.name)».equals(_value)) {
980                                 return "«en.name»";
981                             }
982                             «ENDFOR»
983                             return null;
984                         }
985                     '''
986                 ]
987                 method(Object, "serialize", Object) [
988                     bodyChecked = '''
989                         return toDomValue($1);
990                     '''
991                 ]
992                 method(Object, "fromDomValue", Object) [
993                     modifiers = PUBLIC + FINAL + STATIC
994                     bodyChecked = '''
995                         {
996                             if($1 == null) {
997                                 return null;
998                             }
999                             String _value = (String) $1;
1000                             «FOR en : enumSchema.values»
1001                                 if("«en.name»".equals(_value)) {
1002                                     return «typeSpec.resolvedName».«BindingGeneratorUtil.parseToClassName(en.name)»;
1003                                 }
1004                             «ENDFOR»
1005                             return null;
1006                         }
1007                     '''
1008                 ]
1009                 method(Object, "deserialize", Object) [
1010                     bodyChecked = '''
1011                         return fromDomValue($1);
1012                     '''
1013                 ]
1014             ]
1015
1016             val ret = ctCls.toClassImpl(inputType.classLoader, inputType.protectionDomain)
1017             log.info("DOM Codec for {} was generated {}", inputType, ret)
1018             return ret;
1019         } catch (CodeGenerationException e) {
1020             throw new CodeGenerationException("Cannot compile Transformator for " + inputType, e);
1021         } catch (Exception e) {
1022             log.error("Cannot compile DOM Codec for {}", inputType, e);
1023             val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType);
1024             exception.addSuppressed(e);
1025             throw exception;
1026         }
1027
1028     }
1029
1030     def Class<?> toClassImpl(CtClass newClass, ClassLoader loader, ProtectionDomain domain) {
1031         val cls = newClass.toClass(loader, domain);
1032         if (classFileCapturePath !== null) {
1033             newClass.writeFile(classFileCapturePath.absolutePath);
1034         }
1035         listener?.onCodecCreated(cls);
1036         return cls;
1037     }
1038
1039     def debugWriteClass(CtClass class1) {
1040         val path = class1.name.replace(".", "/") + ".class"
1041
1042         val captureFile = new File(classFileCapturePath, path);
1043         captureFile.createNewFile
1044
1045     }
1046
1047     private def dispatch String deserializeValue(Type type, String domParameter) {
1048         if (INSTANCE_IDENTIFIER.equals(type)) {
1049             return '''(«InstanceIdentifier.name») «INSTANCE_IDENTIFIER_CODEC».deserialize(«domParameter»)'''
1050         } else if (CLASS_TYPE.equals(type)) {
1051             return '''(«Class.name») «IDENTITYREF_CODEC».deserialize(«domParameter»)'''
1052         }
1053         return '''(«type.resolvedName») «domParameter»'''
1054
1055     }
1056
1057     /** 
1058      * Default catch all
1059      * 
1060      **/
1061     private def dispatch CharSequence deserializeProperty(DataSchemaNode container, Type type, String propertyName) '''
1062         «type.resolvedName» «propertyName» = null;
1063     '''
1064
1065     private def dispatch CharSequence deserializeProperty(DataSchemaNode container, GeneratedTypeBuilder type,
1066         String propertyName) {
1067         _deserializeProperty(container, type.toInstance, propertyName)
1068     }
1069
1070     public static def toSetter(String it) {
1071
1072         if (startsWith("is")) {
1073             return "set" + substring(2);
1074         } else if (startsWith("get")) {
1075             return "set" + substring(3);
1076         }
1077         return "set" + it;
1078     }
1079
1080     /* 
1081     private def dispatch CharSequence deserializeProperty(DataSchemaNode container,GeneratedType type, String propertyName) '''
1082         «type.resolvedName» «propertyName» = value.«propertyName»();
1083         if(«propertyName» != null) {
1084             Object domValue = «type.serializer».toDomStatic(QNAME,«propertyName»);
1085             _childNodes.add(domValue);
1086         }
1087     '''
1088     */
1089     private def getBuilderName(GeneratedType type) '''«type.resolvedName»Builder'''
1090
1091     private def staticQNameField(CtClass it, QName node) {
1092         val field = new CtField(ctQName, "QNAME", it);
1093         field.modifiers = PUBLIC + FINAL + STATIC;
1094         addField(field,
1095             '''«QName.asCtClass.name».create("«node.namespace»","«node.formattedRevision»","«node.localName»")''')
1096     }
1097
1098     private def dispatch String serializeBody(GeneratedType type, ListSchemaNode node) '''
1099         {
1100             «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
1101             java.util.List _childNodes = new java.util.ArrayList();
1102             «type.resolvedName» value = («type.resolvedName») $2;
1103             «transformDataContainerBody(type, type.allProperties, node)»
1104             «serializeAugmentations»
1105             return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
1106         }
1107     '''
1108
1109     private def dispatch String serializeBody(GeneratedType type, ContainerSchemaNode node) '''
1110         {
1111             «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
1112             java.util.List _childNodes = new java.util.ArrayList();
1113             «type.resolvedName» value = («type.resolvedName») $2;
1114             «transformDataContainerBody(type, type.allProperties, node)»
1115             «serializeAugmentations»
1116             return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
1117         }
1118     '''
1119
1120     private def dispatch String serializeBody(GeneratedType type, ChoiceCaseNode node) '''
1121         {
1122         «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
1123             java.util.List _childNodes = new java.util.ArrayList();
1124             «type.resolvedName» value = («type.resolvedName») $2;
1125             «transformDataContainerBody(type, type.allProperties, node)»
1126             «serializeAugmentations»
1127             return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
1128         }
1129     '''
1130
1131     private def dispatch String serializeBody(GeneratedType type, SchemaNode node) '''
1132         {
1133         «QName.name» _resultName = «QName.name».create($1,QNAME.getLocalName());
1134             java.util.List _childNodes = new java.util.ArrayList();
1135             «type.resolvedName» value = («type.resolvedName») $2;
1136             return ($r) java.util.Collections.singletonMap(_resultName,_childNodes);
1137         }
1138     '''
1139
1140     private def transformDataContainerBody(Type type, Map<String, Type> properties, DataNodeContainer node) {
1141         val ret = '''
1142             «FOR child : node.childNodes»
1143                 «val signature = properties.getFor(child)»
1144                 «IF signature !== null»
1145                     //System.out.println("«type.name»#«signature.key»" + value.«signature.key»());
1146                     «serializeProperty(child, signature.value, signature.key)»
1147                 «ENDIF»
1148             «ENDFOR»
1149         '''
1150         return ret;
1151     }
1152
1153     private def serializeAugmentations() '''
1154         java.util.List _augmentations = (java.util.List) «AUGMENTATION_CODEC».serialize(value);
1155         if(_augmentations != null) {
1156             _childNodes.addAll(_augmentations);
1157         }
1158     '''
1159
1160     def Entry<String, Type> getFor(Map<String, Type> map, DataSchemaNode node) {
1161         var sig = map.get(node.getterName);
1162         if (sig != null) {
1163             return new SimpleEntry(node.getterName, sig);
1164         }
1165         sig = map.get(node.booleanGetterName);
1166         if (sig != null) {
1167             return new SimpleEntry(node.booleanGetterName, map.get(node.booleanGetterName));
1168         }
1169         return null;
1170     }
1171
1172     private static def String getBooleanGetterName(DataSchemaNode node) {
1173         return "is" + BindingGeneratorUtil.parseToClassName(node.QName.localName);
1174     }
1175
1176     private static def String getGetterName(DataSchemaNode node) {
1177         return "get" + BindingGeneratorUtil.parseToClassName(node.QName.localName);
1178     }
1179
1180     private static def String getGetterName(QName node) {
1181         return "get" + BindingGeneratorUtil.parseToClassName(node.localName);
1182     }
1183
1184     private def dispatch CharSequence serializeProperty(ListSchemaNode schema, ParameterizedType type,
1185         String propertyName) '''
1186         «type.resolvedName» «propertyName» = value.«propertyName»();
1187         //System.out.println("«propertyName»:" + «propertyName»);
1188         if(«propertyName» != null) {
1189             java.util.Iterator _iterator = «propertyName».iterator();
1190             boolean _hasNext = _iterator.hasNext();
1191             while(_hasNext) {
1192                 Object _listItem = _iterator.next();
1193                 Object _domValue = «type.actualTypeArguments.get(0).serializer(schema).resolvedName».toDomStatic(_resultName,_listItem);
1194                 _childNodes.add(_domValue);
1195                 _hasNext = _iterator.hasNext();
1196             }
1197         }
1198     '''
1199
1200     private def dispatch CharSequence serializeProperty(LeafSchemaNode schema, Type type, String propertyName) '''
1201         «type.resolvedName» «propertyName» = value.«propertyName»();
1202         
1203         if(«propertyName» != null) {
1204             «QName.name» _qname = «QName.name».create(_resultName,"«schema.QName.localName»");
1205             Object _propValue = «serializeValue(type, propertyName)»;
1206             if(_propValue != null) {
1207                 Object _domValue = java.util.Collections.singletonMap(_qname,_propValue);
1208                 _childNodes.add(_domValue);
1209             }
1210         }
1211     '''
1212
1213     private def dispatch serializeValue(GeneratedTransferObject type, String parameter) '''«type.valueSerializer.
1214         resolvedName».toDomValue(«parameter»)'''
1215
1216     private def dispatch serializeValue(Enumeration type, String parameter) '''«type.valueSerializer.resolvedName».toDomValue(«parameter»)'''
1217
1218     private def dispatch serializeValue(Type signature, String property) {
1219         if (INSTANCE_IDENTIFIER == signature) {
1220             return '''«INSTANCE_IDENTIFIER_CODEC».serialize(«property»)'''
1221         } else if (CLASS_TYPE.equals(signature)) {
1222             return '''(«QName.resolvedName») «IDENTITYREF_CODEC».serialize(«property»)'''
1223         }
1224         return '''«property»''';
1225     }
1226
1227     private def dispatch CharSequence serializeProperty(LeafListSchemaNode schema, ParameterizedType type,
1228         String propertyName) '''
1229         «type.resolvedName» «propertyName» = value.«propertyName»();
1230         if(«propertyName» != null) {
1231             «QName.name» _qname = «QName.name».create(_resultName,"«schema.QName.localName»");
1232             java.util.Iterator _iterator = «propertyName».iterator();
1233             boolean _hasNext = _iterator.hasNext();
1234             while(_hasNext) {
1235                 Object _listItem = _iterator.next();
1236                 Object _propValue = «serializeValue(type.actualTypeArguments.get(0), "_listItem")»;
1237                 Object _domValue = java.util.Collections.singletonMap(_qname,_propValue);
1238                 _childNodes.add(_domValue);
1239                 _hasNext = _iterator.hasNext();
1240             }
1241         }
1242     '''
1243
1244     private def dispatch CharSequence serializeProperty(ChoiceNode container, GeneratedType type,
1245         String propertyName) '''
1246         «type.resolvedName» «propertyName» = value.«propertyName»();
1247         if(«propertyName» != null) {
1248             java.util.List domValue = «type.serializer(container).resolvedName».toDomStatic(_resultName,«propertyName»);
1249             _childNodes.addAll(domValue);
1250         }
1251     '''
1252
1253     /** 
1254      * Default catch all
1255      * 
1256      **/
1257     private def dispatch CharSequence serializeProperty(DataSchemaNode container, Type type, String propertyName) '''
1258         «type.resolvedName» «propertyName» = value.«propertyName»();
1259         if(«propertyName» != null) {
1260             Object domValue = «propertyName»;
1261             _childNodes.add(domValue);
1262         }
1263     '''
1264
1265     private def dispatch CharSequence serializeProperty(DataSchemaNode container, GeneratedTypeBuilder type,
1266         String propertyName) {
1267         serializeProperty(container, type.toInstance, propertyName)
1268     }
1269
1270     private def dispatch CharSequence serializeProperty(DataSchemaNode container, GeneratedType type,
1271         String propertyName) '''
1272         «type.resolvedName» «propertyName» = value.«propertyName»();
1273         if(«propertyName» != null) {
1274             Object domValue = «type.serializer(container).resolvedName».toDomStatic(_resultName,«propertyName»);
1275             _childNodes.add(domValue);
1276         }
1277     '''
1278
1279     private def codecClassName(GeneratedType typeSpec) {
1280         return '''«typeSpec.resolvedName»$Broker$Codec$DOM'''
1281     }
1282
1283     private def codecClassName(Class<?> typeSpec) {
1284         return '''«typeSpec.name»$Broker$Codec$DOM'''
1285     }
1286
1287     private def HashMap<String, Type> getAllProperties(GeneratedType type) {
1288         val ret = new HashMap<String, Type>();
1289         type.collectAllProperties(ret);
1290         return ret;
1291     }
1292
1293     private def dispatch void collectAllProperties(GeneratedType type, Map<String, Type> set) {
1294         for (definition : type.methodDefinitions) {
1295             set.put(definition.name, definition.returnType);
1296         }
1297         for (property : type.properties) {
1298             set.put(property.getterName, property.returnType);
1299         }
1300         for (parent : type.implements) {
1301             parent.collectAllProperties(set);
1302         }
1303     }
1304
1305     def String getGetterName(GeneratedProperty property) {
1306         return "get" + property.name.toFirstUpper
1307     }
1308
1309     private def dispatch void collectAllProperties(Type type, Map<String, Type> set) {
1310         // NOOP for generic type.
1311     }
1312
1313     def String getResolvedName(Type type) {
1314         return type.asCtClass.name;
1315     }
1316
1317     def String getResolvedName(Class<?> type) {
1318         return type.asCtClass.name;
1319     }
1320
1321     def CtClass asCtClass(Type type) {
1322         val cls = loadClassWithTCCL(type.fullyQualifiedName)
1323         return cls.asCtClass;
1324     }
1325
1326     private def dispatch processException(Class<?> inputType, CodeGenerationException e) {
1327         log.error("Cannot compile DOM Codec for {}. One of it's prerequisites was not generated.", inputType);
1328         throw e;
1329     }
1330
1331     private def dispatch processException(Class<?> inputType, Exception e) {
1332         log.error("Cannot compile DOM Codec for {}", inputType, e);
1333         val exception = new CodeGenerationException("Cannot compile Transformator for " + inputType, e);
1334         throw exception;
1335     }
1336
1337     private def setBodyChecked(CtMethod method, String body) {
1338         try {
1339             method.setBody(body);
1340         } catch (CannotCompileException e) {
1341             log.error("Cannot compile method: {}#{} {}, Reason: {} Body: {}", method.declaringClass, method.name,
1342                 method.signature, e.message, body)
1343             throw e;
1344         }
1345     }
1346
1347     private def <V> V withClassLoaderAndLock(ClassLoader cls, Lock lock, Callable<V> function) throws Exception {
1348         appendClassLoaderIfMissing(cls);
1349         ClassLoaderUtils.withClassLoaderAndLock(cls, lock, function);
1350     }
1351
1352 }
1353
1354 @Data
1355 class PropertyPair {
1356
1357     String getterName;
1358
1359     Type type;
1360
1361     @Property
1362     Type returnType;
1363     @Property
1364     SchemaNode schemaNode;
1365 }