Merge "Fix for Bug 3"
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / sal / binding / dom / serializer / impl / LazyGeneratedCodecRegistry.java
1 package org.opendaylight.controller.sal.binding.dom.serializer.impl;
2
3 import java.awt.CompositeContext;
4 import java.lang.ref.WeakReference;
5 import java.lang.reflect.Field;
6 import java.lang.reflect.ParameterizedType;
7 import java.util.ArrayList;
8 import java.util.Collection;
9 import java.util.Collections;
10 import java.util.HashMap;
11 import java.util.HashSet;
12 import java.util.Iterator;
13 import java.util.List;
14 import java.util.Map;
15 import java.util.Map.Entry;
16 import java.util.Objects;
17 import java.util.concurrent.Callable;
18 import java.util.concurrent.ConcurrentHashMap;
19 import java.util.concurrent.ConcurrentMap;
20 import java.util.Set;
21 import java.util.WeakHashMap;
22
23 import org.apache.commons.lang3.text.translate.AggregateTranslator;
24 import org.opendaylight.controller.sal.binding.dom.serializer.api.AugmentationCodec;
25 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCaseCodec;
26 import org.opendaylight.controller.sal.binding.dom.serializer.api.ChoiceCodec;
27 import org.opendaylight.controller.sal.binding.dom.serializer.api.CodecRegistry;
28 import org.opendaylight.controller.sal.binding.dom.serializer.api.DataContainerCodec;
29 import org.opendaylight.controller.sal.binding.dom.serializer.api.DomCodec;
30 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentifierCodec;
31 import org.opendaylight.controller.sal.binding.dom.serializer.api.IdentitityCodec;
32 import org.opendaylight.controller.sal.binding.dom.serializer.api.InstanceIdentifierCodec;
33 import org.opendaylight.controller.sal.binding.dom.serializer.api.ValueWithQName;
34 import org.opendaylight.controller.sal.binding.impl.util.ClassLoaderUtils;
35 import org.opendaylight.controller.sal.core.api.model.SchemaServiceListener;
36 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
37 import org.opendaylight.yangtools.binding.generator.util.Types;
38 import org.opendaylight.yangtools.concepts.Delegator;
39 import org.opendaylight.yangtools.concepts.Identifiable;
40 import org.opendaylight.yangtools.yang.binding.Augmentable;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
43 import org.opendaylight.yangtools.yang.binding.BindingCodec;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.Identifier;
47 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
50 import org.opendaylight.yangtools.yang.data.api.Node;
51 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
53 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
55 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
62 import org.opendaylight.yangtools.yang.model.api.UsesNode;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 import static com.google.common.base.Preconditions.*;
67 import static org.opendaylight.controller.sal.binding.dom.serializer.impl.IntermediateMapping.*;
68
69 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
70 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
71 import org.opendaylight.yangtools.sal.binding.model.api.Type;
72 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
73 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
74 import org.opendaylight.yangtools.yang.model.api.Module;
75 import org.opendaylight.yangtools.yang.model.util.SchemaContextUtil;
76
77 import com.google.common.collect.FluentIterable;
78 import com.google.common.util.concurrent.CycleDetectingLockFactory.WithExplicitOrdering;
79
80 public class LazyGeneratedCodecRegistry implements //
81         CodecRegistry, //
82         SchemaServiceListener, //
83         GeneratorListener {
84
85     private final static Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
86     private final static LateMixinCodec NOT_READY_CODEC = new LateMixinCodec();
87
88     private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
89     private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
90
91     private TransformerGenerator generator;
92
93     // Concrete class to codecs
94     private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = new WeakHashMap<>();
95     private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = new WeakHashMap<>();
96     private static final Map<Class<?>, ChoiceCodecImpl<?>> choiceCodecs = new WeakHashMap<>();
97     private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = new WeakHashMap<>();
98     private static final Map<Class<?>, AugmentableCompositeCodec> augmentableCodecs = new WeakHashMap<>();
99     private static final Map<Class<?>, AugmentationCodec<?>> augmentationCodecs = new WeakHashMap<>();
100     private static final Map<Class<?>, QName> identityQNames = new WeakHashMap<>();
101     private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
102     /** Binding type to encountered classes mapping **/
103     @SuppressWarnings("rawtypes")
104     private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
105
106     @SuppressWarnings("rawtypes")
107     private static final ConcurrentMap<Type, ChoiceCaseCodecImpl> typeToCaseCodecs = new ConcurrentHashMap<>();
108
109     private CaseClassMapFacade classToCaseRawCodec = new CaseClassMapFacade();
110
111     private static final Map<SchemaPath, GeneratedTypeBuilder> pathToType = new ConcurrentHashMap<>();
112     private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
113     private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
114
115     private SchemaContext currentSchema;
116
117     public TransformerGenerator getGenerator() {
118         return generator;
119     }
120
121     public void setGenerator(TransformerGenerator generator) {
122         this.generator = generator;
123     }
124
125     @Override
126     public InstanceIdentifierCodec getInstanceIdentifierCodec() {
127         return instanceIdentifierCodec;
128     }
129
130     @Override
131     public <T extends Augmentation<?>> AugmentationCodec<T> getCodecForAugmentation(Class<T> object) {
132         AugmentationCodec<T> codec = null;
133         @SuppressWarnings("rawtypes")
134         AugmentationCodec potentialCodec = augmentationCodecs.get(object);
135         if (potentialCodec != null) {
136             codec = potentialCodec;
137         } else
138             try {
139                 Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
140                         .augmentationTransformerFor(object);
141                 BindingCodec<Map<QName, Object>, Object> rawCodec = augmentRawCodec.newInstance();
142                 codec = new AugmentationCodecWrapper<T>(rawCodec);
143                 augmentationCodecs.put(augmentRawCodec, codec);
144             } catch (InstantiationException e) {
145                 LOG.error("Can not instantiate raw augmentation codec {}", object.getSimpleName(), e);
146             } catch (IllegalAccessException e) {
147                 LOG.debug("BUG: Constructor for {} is not accessible.", object.getSimpleName(), e);
148             }
149         Class<? extends Augmentable<?>> objectSupertype = getAugmentableArgumentFrom(object);
150         if (objectSupertype != null) {
151             getAugmentableCodec(objectSupertype).addAugmentationCodec(object, codec);
152         } else {
153             LOG.warn("Could not find augmentation target for augmentation {}", object);
154         }
155         return codec;
156     }
157     
158     @Override
159     public QName getQNameForAugmentation(Class<?> cls) {
160         checkArgument(Augmentation.class.isAssignableFrom(cls));
161         return getCodecForAugmentation((Class<? extends Augmentation>)cls).getAugmentationQName();
162     }
163
164     private static Class<? extends Augmentable<?>> getAugmentableArgumentFrom(
165             final Class<? extends Augmentation<?>> augmentation) {
166         try {
167             Class<? extends Augmentable<?>> ret = ClassLoaderUtils.withClassLoader(augmentation.getClassLoader(),
168                     new Callable<Class<? extends Augmentable<?>>>() {
169                         @Override
170                         @SuppressWarnings("unchecked")
171                         public Class<? extends Augmentable<?>> call() throws Exception {
172                             for (java.lang.reflect.Type supertype : augmentation.getGenericInterfaces()) {
173                                 if (supertype instanceof ParameterizedType
174                                         && Augmentation.class.equals(((ParameterizedType) supertype).getRawType())) {
175                                     ParameterizedType augmentationGeneric = (ParameterizedType) supertype;
176                                     return (Class<? extends Augmentable<?>>) augmentationGeneric
177                                             .getActualTypeArguments()[0];
178                                 }
179                             }
180                             return null;
181                         }
182                     });
183             return ret;
184         } catch (Exception e) {
185             LOG.debug("Could not find augmentable for {} using {}", augmentation, augmentation.getClassLoader(), e);
186             return null;
187         }
188     }
189
190     @Override
191     public Class<?> getClassForPath(List<QName> names) {
192         DataSchemaNode node = getSchemaNode(names);
193         SchemaPath path = node.getPath();
194         Type type = pathToType.get(path);
195         if (type != null) {
196             type = new ReferencedTypeImpl(type.getPackageName(), type.getName());
197         } else {
198             type = pathToInstantiatedType.get(names);
199         }
200         @SuppressWarnings("rawtypes")
201         WeakReference<Class> weakRef = typeToClass.get(type);
202         if (weakRef == null) {
203             LOG.error("Could not find loaded class for path: {} and type: {}", path, type.getFullyQualifiedName());
204         }
205         return weakRef.get();
206     }
207
208     @Override
209     public void putPathToClass(List<QName> names, Class<?> cls) {
210         Type reference = Types.typeForClass(cls);
211         pathToInstantiatedType.put(names, reference);
212         bindingClassEncountered(cls);
213     }
214
215     @Override
216     public IdentifierCodec<?> getKeyCodecForPath(List<QName> names) {
217         @SuppressWarnings("unchecked")
218         Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
219         return getIdentifierCodecForIdentifiable(cls);
220     }
221
222     @Override
223     public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(Class<T> type) {
224         @SuppressWarnings("unchecked")
225         DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
226         if (ret != null) {
227             return ret;
228         }
229         Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
230         BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
231         DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
232         containerCodecs.put(type, newWrapper);
233         return newWrapper;
234     }
235
236     @SuppressWarnings("rawtypes")
237     public void bindingClassEncountered(Class cls) {
238
239         ConcreteType typeRef = Types.typeForClass(cls);
240         if (typeToClass.containsKey(typeRef)) {
241             return;
242         }
243         LOG.trace("Binding Class {} encountered.", cls);
244         WeakReference<Class> weakRef = new WeakReference<>(cls);
245         typeToClass.put(typeRef, weakRef);
246         if (Augmentation.class.isAssignableFrom(cls)) {
247
248         } else if (DataObject.class.isAssignableFrom(cls)) {
249             @SuppressWarnings({ "unchecked", "unused" })
250             Object cdc = getCodecForDataObject((Class<? extends DataObject>) cls);
251         }
252     }
253
254     @Override
255     public void onClassProcessed(Class<?> cls) {
256         ConcreteType typeRef = Types.typeForClass(cls);
257         if (typeToClass.containsKey(typeRef)) {
258             return;
259         }
260         LOG.trace("Binding Class {} encountered.", cls);
261         WeakReference<Class> weakRef = new WeakReference<>((Class) cls);
262         typeToClass.put(typeRef, weakRef);
263     }
264
265     private DataSchemaNode getSchemaNode(List<QName> path) {
266         QName firstNode = path.get(0);
267         DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
268                 firstNode.getRevision());
269         Iterator<QName> iterator = path.iterator();
270         while (iterator.hasNext()) {
271             QName arg = iterator.next();
272             DataSchemaNode currentNode = previous.getDataChildByName(arg);
273             if (currentNode == null && previous instanceof DataNodeContainer) {
274                 currentNode = searchInChoices(previous, arg);
275             }
276             if (currentNode instanceof DataNodeContainer) {
277                 previous = (DataNodeContainer) currentNode;
278             } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
279                 checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
280                 return currentNode;
281             }
282         }
283         return (DataSchemaNode) previous;
284     }
285
286     private DataSchemaNode searchInChoices(DataNodeContainer node, QName arg) {
287         Set<DataSchemaNode> children = node.getChildNodes();
288         for (DataSchemaNode child : children) {
289             if (child instanceof ChoiceNode) {
290                 ChoiceNode choiceNode = (ChoiceNode) child;
291                 DataSchemaNode potential = searchInCases(choiceNode, arg);
292                 if (potential != null) {
293                     return potential;
294                 }
295             }
296         }
297         return null;
298     }
299
300     private DataSchemaNode searchInCases(ChoiceNode choiceNode, QName arg) {
301         Set<ChoiceCaseNode> cases = choiceNode.getCases();
302         for (ChoiceCaseNode caseNode : cases) {
303             DataSchemaNode node = caseNode.getDataChildByName(arg);
304             if (node != null) {
305                 return node;
306             }
307         }
308         return null;
309     }
310
311     private <T> T newInstanceOf(Class<?> newType) {
312         try {
313             @SuppressWarnings("unchecked")
314             T ret = (T) newType.newInstance();
315             return ret;
316         } catch (InstantiationException e) {
317             throw new IllegalStateException(e);
318         } catch (IllegalAccessException e) {
319             throw new IllegalStateException(e);
320         }
321     }
322
323     @Override
324     public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(Class<T> type) {
325         IdentifierCodec<?> obj = identifierCodecs.get(type);
326         if (obj != null) {
327             return obj;
328         }
329         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
330                 .keyTransformerForIdentifiable(type);
331         BindingCodec<Map<QName, Object>, Object> newInstance;
332         newInstance = newInstanceOf(newCodec);
333         IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
334         identifierCodecs.put(type, newWrapper);
335         return newWrapper;
336     }
337
338     @Override
339     public IdentitityCodec<?> getIdentityCodec() {
340         return identityRefCodec;
341     }
342
343     @Override
344     public <T extends BaseIdentity> IdentitityCodec<T> getCodecForIdentity(Class<T> codec) {
345         bindingClassEncountered(codec);
346         return identityRefCodec;
347     }
348
349     @Override
350     public void onCodecCreated(Class<?> cls) {
351         CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
352         CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
353     }
354
355     @Override
356     public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(Class<T> object) {
357         @SuppressWarnings("unchecked")
358         IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
359         if (obj != null) {
360             return obj;
361         }
362         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
363                 .keyTransformerForIdentifier(object);
364         BindingCodec<Map<QName, Object>, Object> newInstance;
365         newInstance = newInstanceOf(newCodec);
366         IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
367         identifierCodecs.put(object, newWrapper);
368         return newWrapper;
369     }
370
371     @SuppressWarnings("rawtypes")
372     public ChoiceCaseCodecImpl getCaseCodecFor(Class caseClass) {
373         ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
374         if (potential != null) {
375             return potential;
376         }
377         ConcreteType typeref = Types.typeForClass(caseClass);
378         ChoiceCaseCodecImpl caseCodec = typeToCaseCodecs.get(typeref);
379
380         checkState(caseCodec != null, "Case Codec was not created proactivelly for %s", caseClass.getName());
381         checkState(caseCodec.getSchema() != null, "Case schema is not available for %s", caseClass.getName());
382         @SuppressWarnings("unchecked")
383         Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseCodec.getSchema());
384         BindingCodec newInstance = newInstanceOf(newCodec);
385         caseCodec.setDelegate(newInstance);
386         caseCodecs.put(caseClass, caseCodec);
387
388         for (Entry<Class<?>, ChoiceCodecImpl<?>> choice : choiceCodecs.entrySet()) {
389             if (choice.getKey().isAssignableFrom(caseClass)) {
390                 choice.getValue().cases.put(caseClass, caseCodec);
391             }
392         }
393         return caseCodec;
394     }
395
396     public void onModuleContextAdded(SchemaContext schemaContext, Module module, ModuleContext context) {
397         pathToType.putAll(context.getChildNodes());
398         qnamesToIdentityMap.putAll(context.getIdentities());
399         for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
400             typeToQname.put(
401                     new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
402                     identity.getKey());
403         }
404         captureCases(context.getCases(), schemaContext);
405     }
406
407     private void captureCases(Map<SchemaPath, GeneratedTypeBuilder> cases, SchemaContext module) {
408         for (Entry<SchemaPath, GeneratedTypeBuilder> caseNode : cases.entrySet()) {
409             ReferencedTypeImpl typeref = new ReferencedTypeImpl(caseNode.getValue().getPackageName(), caseNode
410                     .getValue().getName());
411
412             pathToType.put(caseNode.getKey(), caseNode.getValue());
413
414             ChoiceCaseNode node = (ChoiceCaseNode) SchemaContextUtil.findDataSchemaNode(module, caseNode.getKey());
415
416             if (node == null) {
417                 LOG.error("YANGTools Bug: SchemaNode for {}, with path {} was not found in context.",
418                         typeref.getFullyQualifiedName(), caseNode.getKey());
419                 @SuppressWarnings("rawtypes")
420                 ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl();
421                 typeToCaseCodecs.putIfAbsent(typeref, value);
422                 continue;
423             }
424             @SuppressWarnings("rawtypes")
425             ChoiceCaseCodecImpl value = new ChoiceCaseCodecImpl(node);
426             typeToCaseCodecs.putIfAbsent(typeref, value);
427         }
428     }
429
430     @Override
431     public void onGlobalContextUpdated(SchemaContext context) {
432         currentSchema = context;
433     }
434
435     @SuppressWarnings({ "unchecked", "rawtypes" })
436     @Override
437     public void onChoiceCodecCreated(Class<?> choiceClass,
438             Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, ChoiceNode schema) {
439         ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
440         checkState(oldCodec == null);
441         BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
442         ChoiceCodecImpl<?> newCodec = new ChoiceCodecImpl(delegate);
443         choiceCodecs.put(choiceClass, newCodec);
444         CodecMapping.setClassToCaseMap(choiceCodec, (Map<Class<?>, BindingCodec<?, ?>>) classToCaseRawCodec);
445         CodecMapping.setCompositeNodeToCaseMap(choiceCodec, newCodec.getCompositeToCase());
446
447         tryToCreateCasesCodecs(schema);
448
449     }
450
451     private void tryToCreateCasesCodecs(ChoiceNode schema) {
452         for (ChoiceCaseNode caseNode : schema.getCases()) {
453             SchemaPath path = caseNode.getPath();
454             GeneratedTypeBuilder type;
455             if (path != null && (type = pathToType.get(path)) != null) {
456                 ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
457                 ChoiceCaseCodecImpl partialCodec = typeToCaseCodecs.get(typeref);
458                 if (partialCodec.getSchema() == null) {
459                     partialCodec.setSchema(caseNode);
460                 }
461
462                 Class<?> caseClass = ClassLoaderUtils.tryToLoadClassWithTCCL(type.getFullyQualifiedName());
463                 if (caseClass != null) {
464                     getCaseCodecFor(caseClass);
465                 }
466             }
467         }
468
469     }
470
471     @Override
472     public void onValueCodecCreated(Class<?> valueClass, Class<?> valueCodec) {
473     }
474
475     @Override
476     public void onCaseCodecCreated(Class<?> choiceClass,
477             Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
478     }
479
480     @Override
481     public void onDataContainerCodecCreated(Class<?> dataClass, Class<? extends BindingCodec<?, ?>> dataCodec) {
482         if (Augmentable.class.isAssignableFrom(dataClass)) {
483             AugmentableCompositeCodec augmentableCodec = getAugmentableCodec(dataClass);
484             CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
485         }
486
487     }
488
489     public AugmentableCompositeCodec getAugmentableCodec(Class<?> dataClass) {
490         AugmentableCompositeCodec ret = augmentableCodecs.get(dataClass);
491         if (ret != null) {
492             return ret;
493         }
494         ret = new AugmentableCompositeCodec(dataClass);
495         augmentableCodecs.put(dataClass, ret);
496         return ret;
497     }
498
499     private static abstract class IntermediateCodec<T> implements //
500             DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
501
502         private final BindingCodec<Map<QName, Object>, Object> delegate;
503
504         @Override
505         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
506             return delegate;
507         }
508
509         public IntermediateCodec(BindingCodec<Map<QName, Object>, Object> delegate) {
510             this.delegate = delegate;
511         }
512
513         @Override
514         public Node<?> serialize(ValueWithQName<T> input) {
515             Map<QName, Object> intermediateOutput = delegate.serialize(input);
516             return toNode(intermediateOutput);
517         }
518     }
519
520     private static class IdentifierCodecImpl<T extends Identifier<?>> //
521             extends IntermediateCodec<T> //
522             implements IdentifierCodec<T> {
523
524         public IdentifierCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
525             super(delegate);
526         }
527
528         @Override
529         public ValueWithQName<T> deserialize(Node<?> input) {
530             QName qname = input.getNodeType();
531             @SuppressWarnings("unchecked")
532             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
533             return new ValueWithQName<T>(qname, value);
534         }
535
536         @Override
537         public CompositeNode serialize(ValueWithQName<T> input) {
538             return (CompositeNode) super.serialize(input);
539         }
540     }
541
542     private static class DataContainerCodecImpl<T extends DataContainer> //
543             extends IntermediateCodec<T> //
544             implements DataContainerCodec<T> {
545
546         public DataContainerCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
547             super(delegate);
548         }
549
550         @Override
551         public ValueWithQName<T> deserialize(Node<?> input) {
552             if (input == null) {
553                 return null;
554             }
555             QName qname = input.getNodeType();
556             @SuppressWarnings("unchecked")
557             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
558             return new ValueWithQName<T>(qname, value);
559         }
560
561         @Override
562         public CompositeNode serialize(ValueWithQName<T> input) {
563             return (CompositeNode) super.serialize(input);
564         }
565     }
566
567     @SuppressWarnings("rawtypes")
568     private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
569             Delegator<BindingCodec> {
570         private boolean augmenting;
571         private BindingCodec delegate;
572
573         private Set<String> validNames;
574         private Set<QName> validQNames;
575         private ChoiceCaseNode schema;
576
577         public void setSchema(ChoiceCaseNode caseNode) {
578             this.schema = schema;
579             this.schema = caseNode;
580             validNames = new HashSet<>();
581             validQNames = new HashSet<>();
582             for (DataSchemaNode node : caseNode.getChildNodes()) {
583                 QName qname = node.getQName();
584                 validQNames.add(qname);
585                 validNames.add(qname.getLocalName());
586             }
587             augmenting = caseNode.isAugmenting();
588         }
589
590         public ChoiceCaseCodecImpl() {
591             this.delegate = NOT_READY_CODEC;
592         }
593
594         public ChoiceCaseCodecImpl(ChoiceCaseNode caseNode) {
595             this.delegate = NOT_READY_CODEC;
596             setSchema(caseNode);
597         }
598
599         @Override
600         public ValueWithQName<T> deserialize(Node<?> input) {
601             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
602         }
603
604         @Override
605         public CompositeNode serialize(ValueWithQName<T> input) {
606             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
607         }
608
609         public BindingCodec getDelegate() {
610             return delegate;
611         }
612
613         public void setDelegate(BindingCodec delegate) {
614             this.delegate = delegate;
615         }
616
617         public ChoiceCaseNode getSchema() {
618             return schema;
619         }
620
621         @Override
622         public boolean isAcceptable(Node<?> input) {
623             if (input instanceof CompositeNode) {
624                 if (augmenting) {
625                     return checkAugmenting((CompositeNode) input);
626                 } else {
627                     return checkLocal((CompositeNode) input);
628                 }
629             }
630             return false;
631         }
632
633         private boolean checkLocal(CompositeNode input) {
634             QName parent = input.getNodeType();
635             for (Node<?> childNode : input.getChildren()) {
636                 QName child = childNode.getNodeType();
637                 if (!Objects.equals(parent.getNamespace(), child.getNamespace())
638                         || !Objects.equals(parent.getRevision(), child.getRevision())) {
639                     continue;
640                 }
641                 if (validNames.contains(child.getLocalName())) {
642                     return true;
643                 }
644             }
645             return false;
646         }
647
648         private boolean checkAugmenting(CompositeNode input) {
649             for (Node<?> child : input.getChildren()) {
650                 if (validQNames.contains(child.getNodeType())) {
651                     return true;
652                 }
653             }
654             return false;
655         }
656     }
657
658     private static class ChoiceCodecImpl<T> implements ChoiceCodec<T> {
659
660         private final BindingCodec<Map<QName, Object>, Object> delegate;
661
662         @SuppressWarnings("rawtypes")
663         private final Map<Class, ChoiceCaseCodecImpl<?>> cases = new WeakHashMap<>();
664
665         private final CaseCompositeNodeMapFacade CompositeToCase;
666
667         public ChoiceCodecImpl(BindingCodec<Map<QName, Object>, Object> delegate) {
668             this.delegate = delegate;
669             this.CompositeToCase = new CaseCompositeNodeMapFacade(cases);
670         }
671
672         @Override
673         public ValueWithQName<T> deserialize(Node<?> input) {
674             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
675         }
676
677         @Override
678         public Node<?> serialize(ValueWithQName<T> input) {
679             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
680         }
681
682         public CaseCompositeNodeMapFacade getCompositeToCase() {
683             return CompositeToCase;
684         }
685
686         public Map<Class, ChoiceCaseCodecImpl<?>> getCases() {
687             return cases;
688         }
689
690         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
691             return delegate;
692         }
693
694     }
695
696     @SuppressWarnings("rawtypes")
697     private class CaseClassMapFacade extends MapFacadeBase {
698
699         @Override
700         public Set<java.util.Map.Entry<Class, BindingCodec<Object, Object>>> entrySet() {
701             return Collections.emptySet();
702         }
703
704         @Override
705         public BindingCodec get(Object key) {
706             if (key instanceof Class) {
707                 Class cls = (Class) key;
708                 // bindingClassEncountered(cls);
709                 ChoiceCaseCodecImpl caseCodec = getCaseCodecFor(cls);
710                 return caseCodec.getDelegate();
711             }
712             return null;
713         }
714     }
715
716     @SuppressWarnings("rawtypes")
717     private static class CaseCompositeNodeMapFacade extends MapFacadeBase<CompositeNode> {
718
719         final Map<Class, ChoiceCaseCodecImpl<?>> choiceCases;
720
721         public CaseCompositeNodeMapFacade(Map<Class, ChoiceCaseCodecImpl<?>> choiceCases) {
722             this.choiceCases = choiceCases;
723         }
724
725         @Override
726         public BindingCodec get(Object key) {
727             if (!(key instanceof CompositeNode)) {
728                 return null;
729             }
730             for (java.util.Map.Entry<Class, ChoiceCaseCodecImpl<?>> entry : choiceCases.entrySet()) {
731                 ChoiceCaseCodecImpl<?> codec = entry.getValue();
732                 if (codec.isAcceptable((CompositeNode) key)) {
733                     return codec.getDelegate();
734                 }
735             }
736             return null;
737         }
738
739     }
740
741     /**
742      * This map is used as only facade for {@link BindingCodec} in different
743      * classloaders to retrieve codec dynamicly based on provided key.
744      * 
745      * @param <T>
746      *            Key type
747      */
748     @SuppressWarnings("rawtypes")
749     private static abstract class MapFacadeBase<T> implements Map<T, BindingCodec<?, ?>> {
750
751         @Override
752         public boolean containsKey(Object key) {
753             return get(key) != null;
754         }
755
756         @Override
757         public void clear() {
758             throw notModifiable();
759         }
760
761         @Override
762         public boolean equals(Object obj) {
763             return super.equals(obj);
764         }
765
766         @Override
767         public BindingCodec remove(Object key) {
768             return null;
769         }
770
771         @Override
772         public int size() {
773             return 0;
774         }
775
776         @Override
777         public Collection<BindingCodec<?, ?>> values() {
778             return Collections.emptySet();
779         }
780
781         private UnsupportedOperationException notModifiable() {
782             return new UnsupportedOperationException("Not externally modifiable.");
783         }
784
785         @Override
786         public BindingCodec<Map<QName, Object>, Object> put(T key, BindingCodec<?, ?> value) {
787             throw notModifiable();
788         }
789
790         @Override
791         public void putAll(Map<? extends T, ? extends BindingCodec<?, ?>> m) {
792             throw notModifiable();
793         }
794
795         @Override
796         public int hashCode() {
797             return super.hashCode();
798         }
799
800         @Override
801         public boolean isEmpty() {
802             return true;
803         }
804
805         @Override
806         public Set<T> keySet() {
807             return Collections.emptySet();
808         }
809
810         @Override
811         public Set<java.util.Map.Entry<T, BindingCodec<?, ?>>> entrySet() {
812             return Collections.emptySet();
813         }
814
815         @Override
816         public boolean containsValue(Object value) {
817             return false;
818         }
819     }
820
821     @SuppressWarnings({ "rawtypes", "unchecked" })
822     private class AugmentableCompositeCodec implements BindingCodec {
823
824         private final Class augmentableType;
825
826         Map<Class, AugmentationCodec<?>> localAugmentationCodecs = new WeakHashMap<>();
827
828         public AugmentableCompositeCodec(Class type) {
829             checkArgument(Augmentable.class.isAssignableFrom(type));
830             augmentableType = type;
831         }
832
833         @Override
834         public Object serialize(Object input) {
835             if (input instanceof Augmentable<?>) {
836
837                 Map<Class, Augmentation> augmentations = getAugmentations(input);
838                 return serializeImpl(augmentations);
839             }
840             return null;
841         }
842
843         private Map<Class, Augmentation> getAugmentations(Object input) {
844             Field augmentationField;
845             try {
846                 augmentationField = input.getClass().getDeclaredField("augmentation");
847                 augmentationField.setAccessible(true);
848                 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
849                 return augMap;
850             } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
851                 LOG.debug("Could not read augmentations for {}", input, e);
852             }
853             return Collections.emptyMap();
854         }
855
856         private List serializeImpl(Map<Class, Augmentation> input) {
857             List ret = new ArrayList<>();
858             for (Entry<Class, Augmentation> entry : input.entrySet()) {
859                 AugmentationCodec codec = getCodecForAugmentation(entry.getKey());
860                 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
861                 ret.addAll(node.getChildren());
862             }
863             return ret;
864         }
865
866         public synchronized <T extends Augmentation<?>> void addAugmentationCodec(Class<T> augmentationClass,
867                 AugmentationCodec<T> value) {
868             localAugmentationCodecs.put(augmentationClass, value);
869         }
870
871         @Override
872         public Map<Class, Augmentation> deserialize(Object input) {
873             Map<Class, Augmentation> ret = new HashMap<>();
874             if (input instanceof CompositeNode) {
875                 List<Entry<Class, AugmentationCodec<?>>> codecs = new ArrayList<>(localAugmentationCodecs.entrySet());
876                 for (Entry<Class, AugmentationCodec<?>> codec : codecs) {
877                     ValueWithQName<?> value = codec.getValue().deserialize((CompositeNode) input);
878                     if (value != null && value.getValue() != null) {
879                         ret.put(codec.getKey(), (Augmentation) value.getValue());
880                     }
881                 }
882             }
883             return ret;
884         }
885
886         public Class getAugmentableType() {
887             return augmentableType;
888         }
889     }
890
891     @SuppressWarnings({ "rawtypes", "unchecked" })
892     private static class LateMixinCodec implements BindingCodec, Delegator<BindingCodec> {
893
894         private BindingCodec delegate;
895
896         @Override
897         public BindingCodec getDelegate() {
898             if (delegate == null) {
899                 throw new IllegalStateException("Codec not initialized yet.");
900             }
901             return delegate;
902         }
903
904         @Override
905         public Object deserialize(Object input) {
906             return getDelegate().deserialize(input);
907         }
908
909         @Override
910         public Object serialize(Object input) {
911             return getDelegate().serialize(input);
912         }
913     }
914
915     private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
916             Delegator<BindingCodec> {
917
918         private BindingCodec delegate;
919         private QName augmentationQName;
920
921         public AugmentationCodecWrapper(BindingCodec<Map<QName, Object>, Object> rawCodec) {
922             this.delegate = rawCodec;
923             this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
924         }
925
926         @Override
927         public BindingCodec getDelegate() {
928             return delegate;
929         }
930
931         @Override
932         public CompositeNode serialize(ValueWithQName<T> input) {
933             @SuppressWarnings("unchecked")
934             List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
935             List<Node<?>> serialized = new ArrayList<>(rawValues.size());
936             for (Map<QName, Object> val : rawValues) {
937                 serialized.add(toNode(val));
938             }
939             return new CompositeNodeTOImpl(input.getQname(), null, serialized);
940         }
941
942         @Override
943         @SuppressWarnings("unchecked")
944         public ValueWithQName<T> deserialize(Node<?> input) {
945             Object rawCodecValue = getDelegate().deserialize((Map<QName, Object>) input);
946             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
947         }
948         
949         @Override
950         public QName getAugmentationQName() {
951             return augmentationQName;
952         }
953     }
954
955     private class IdentityCompositeCodec implements IdentitityCodec {
956
957         @Override
958         public Object deserialize(Object input) {
959             checkArgument(input instanceof QName);
960             return deserialize((QName) input);
961         }
962
963         @Override
964         public Class<?> deserialize(QName input) {
965             Type type = qnamesToIdentityMap.get(input);
966             if (type == null) {
967                 return null;
968             }
969             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
970             WeakReference<Class> softref = typeToClass.get(typeref);
971             if (softref == null) {
972                 return null;
973             }
974             return softref.get();
975         }
976
977         @Override
978         public QName serialize(Class input) {
979             checkArgument(BaseIdentity.class.isAssignableFrom(input));
980             bindingClassEncountered(input);
981             QName qname = identityQNames.get(input);
982             if (qname != null) {
983                 return qname;
984             }
985             ConcreteType typeref = Types.typeForClass(input);
986             qname = typeToQname.get(typeref);
987             if (qname != null) {
988                 identityQNames.put(input, qname);
989             }
990             return qname;
991         }
992
993         @Override
994         public Object serialize(Object input) {
995             checkArgument(input instanceof Class);
996             return serialize((Class) input);
997         }
998     }
999
1000     public boolean isCodecAvailable(Class<? extends DataContainer> cls) {
1001         if (containerCodecs.containsKey(cls)) {
1002             return true;
1003         }
1004         if (identifierCodecs.containsKey(cls)) {
1005             return true;
1006         }
1007         if (choiceCodecs.containsKey(cls)) {
1008             return true;
1009         }
1010         if (caseCodecs.containsKey(cls)) {
1011             return true;
1012         }
1013         if (augmentableCodecs.containsKey(cls)) {
1014             return true;
1015         }
1016         if (augmentationCodecs.containsKey(cls)) {
1017             return true;
1018         }
1019         return false;
1020     }
1021 }