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