Merge "BUG-1276: fixed generated union constructor"
[yangtools.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / generator / impl / LazyGeneratedCodecRegistry.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.sal.binding.generator.impl;
9
10 import java.lang.ref.WeakReference;
11 import java.lang.reflect.Field;
12 import java.util.AbstractMap.SimpleEntry;
13 import java.util.ArrayList;
14 import java.util.Collection;
15 import java.util.Collections;
16 import java.util.HashMap;
17 import java.util.HashSet;
18 import java.util.Iterator;
19 import java.util.List;
20 import java.util.Map;
21 import java.util.Map.Entry;
22 import java.util.Set;
23 import java.util.WeakHashMap;
24 import java.util.concurrent.ConcurrentHashMap;
25 import java.util.concurrent.ConcurrentMap;
26
27 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
28 import org.opendaylight.yangtools.binding.generator.util.Types;
29 import org.opendaylight.yangtools.concepts.Delegator;
30 import org.opendaylight.yangtools.concepts.Identifiable;
31 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
32 import org.opendaylight.yangtools.sal.binding.generator.util.CodeGenerationException;
33 import org.opendaylight.yangtools.sal.binding.model.api.ConcreteType;
34 import org.opendaylight.yangtools.sal.binding.model.api.Type;
35 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTOBuilder;
36 import org.opendaylight.yangtools.yang.binding.Augmentable;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
39 import org.opendaylight.yangtools.yang.binding.BindingCodec;
40 import org.opendaylight.yangtools.yang.binding.BindingMapping;
41 import org.opendaylight.yangtools.yang.binding.DataContainer;
42 import org.opendaylight.yangtools.yang.binding.DataObject;
43 import org.opendaylight.yangtools.yang.binding.Identifier;
44 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
45 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
46 import org.opendaylight.yangtools.yang.common.QName;
47 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
48 import org.opendaylight.yangtools.yang.data.api.Node;
49 import org.opendaylight.yangtools.yang.data.impl.CompositeNodeTOImpl;
50 import org.opendaylight.yangtools.yang.data.impl.codec.AugmentationCodec;
51 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCaseCodec;
52 import org.opendaylight.yangtools.yang.data.impl.codec.ChoiceCodec;
53 import org.opendaylight.yangtools.yang.data.impl.codec.CodecRegistry;
54 import org.opendaylight.yangtools.yang.data.impl.codec.DataContainerCodec;
55 import org.opendaylight.yangtools.yang.data.impl.codec.DomCodec;
56 import org.opendaylight.yangtools.yang.data.impl.codec.IdentifierCodec;
57 import org.opendaylight.yangtools.yang.data.impl.codec.IdentityCodec;
58 import org.opendaylight.yangtools.yang.data.impl.codec.InstanceIdentifierCodec;
59 import org.opendaylight.yangtools.yang.data.impl.codec.ValueWithQName;
60 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
61 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
62 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
63 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
64 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
67 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.Module;
69 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
70 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
71 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75 import com.google.common.base.Optional;
76 import com.google.common.base.Preconditions;
77 import com.google.common.collect.BiMap;
78 import com.google.common.collect.HashBiMap;
79 import com.google.common.collect.HashMultimap;
80 import com.google.common.collect.Iterables;
81 import com.google.common.collect.Multimap;
82 import com.google.common.collect.Multimaps;
83
84 class LazyGeneratedCodecRegistry implements //
85         CodecRegistry, //
86         SchemaContextListener, //
87         GeneratorListener {
88
89     private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
90
91     // Concrete class to codecs
92     private static final Map<Class<?>, DataContainerCodec<?>> containerCodecs = Collections
93             .synchronizedMap(new WeakHashMap<Class<?>, DataContainerCodec<?>>());
94     private static final Map<Class<?>, IdentifierCodec<?>> identifierCodecs = Collections
95             .synchronizedMap(new WeakHashMap<Class<?>, IdentifierCodec<?>>());
96     private static final Map<Class<?>, PublicChoiceCodecImpl<?>> choiceCodecs = Collections
97             .synchronizedMap(new WeakHashMap<Class<?>, PublicChoiceCodecImpl<?>>());
98     private static final Map<Class<?>, ChoiceCaseCodecImpl<?>> caseCodecs = Collections
99             .synchronizedMap(new WeakHashMap<Class<?>, ChoiceCaseCodecImpl<?>>());
100     private static final Map<Class<?>, AugmentableDispatchCodec> augmentableCodecs = Collections
101             .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
102     private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
103             .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
104
105     private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
106             .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
107
108     private static final Map<Class<?>, QName> identityQNames = Collections
109             .synchronizedMap(new WeakHashMap<Class<?>, QName>());
110     private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
111     /** Binding type to encountered classes mapping **/
112     @SuppressWarnings("rawtypes")
113     private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
114
115     private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
116
117     private static final Map<SchemaPath, Type> pathToType = new ConcurrentHashMap<>();
118     private static final Map<List<QName>, Type> pathToInstantiatedType = new ConcurrentHashMap<>();
119     private static final Map<Type, QName> typeToQname = new ConcurrentHashMap<>();
120     private static final BiMap<Type, AugmentationSchema> typeToAugment = HashBiMap
121             .create(new ConcurrentHashMap<Type, AugmentationSchema>());
122
123     private static final Multimap<Type, Type> augmentableToAugmentations = Multimaps.synchronizedMultimap(HashMultimap
124             .<Type, Type> create());
125     private static final Multimap<Type, Type> choiceToCases = Multimaps.synchronizedMultimap(HashMultimap
126             .<Type, Type> create());
127
128     private final InstanceIdentifierCodec instanceIdentifierCodec = new InstanceIdentifierCodecImpl(this);
129     private final IdentityCompositeCodec identityRefCodec = new IdentityCompositeCodec();
130     private final ClassLoadingStrategy classLoadingStrategy;
131     private final AbstractTransformerGenerator generator;
132     private final SchemaLock lock;
133
134     // FIXME: how is this protected?
135     private SchemaContext currentSchema;
136
137     LazyGeneratedCodecRegistry(final SchemaLock lock, final AbstractTransformerGenerator generator,
138             final ClassLoadingStrategy classLoadingStrategy) {
139         this.lock = Preconditions.checkNotNull(lock);
140         this.classLoadingStrategy = Preconditions.checkNotNull(classLoadingStrategy);
141         this.generator = Preconditions.checkNotNull(generator);
142     }
143
144     public SchemaLock getLock() {
145         return lock;
146     }
147
148     @Override
149     public InstanceIdentifierCodec getInstanceIdentifierCodec() {
150         return instanceIdentifierCodec;
151     }
152
153     @SuppressWarnings("unchecked")
154     @Override
155     public <T extends Augmentation<?>> AugmentationCodecWrapper<T> getCodecForAugmentation(final Class<T> augClass) {
156         AugmentationCodecWrapper<T> codec = null;
157         @SuppressWarnings("rawtypes")
158         AugmentationCodecWrapper potentialCodec = augmentationCodecs.get(augClass);
159         if (potentialCodec != null) {
160             codec = potentialCodec;
161         } else {
162             lock.waitForSchema(augClass);
163             Class<? extends BindingCodec<Map<QName, Object>, Object>> augmentRawCodec = generator
164                     .augmentationTransformerFor(augClass);
165
166             BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(augmentRawCodec);
167             codec = new AugmentationCodecWrapper<T>(rawCodec, augClass);
168             augmentationCodecs.put(augClass, codec);
169         }
170
171         final Class<? extends Augmentable<?>> objectSupertype;
172         try {
173             objectSupertype = BindingReflections.findAugmentationTarget(augClass);
174         } catch (Exception e) {
175             LOG.warn("Failed to find target for augmentation {}, ignoring it", augClass, e);
176             return codec;
177         }
178
179         if (objectSupertype == null) {
180             LOG.warn("Augmentation target for {} not found, ignoring it", augClass);
181             return codec;
182         }
183
184         getAugmentableCodec(objectSupertype).addImplementation(codec);
185         return codec;
186     }
187
188     @SuppressWarnings("unchecked")
189     @Override
190     public QName getQNameForAugmentation(final Class<?> cls) {
191         Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
192         return getCodecForAugmentation((Class<? extends Augmentation<?>>) cls).getAugmentationQName();
193     }
194
195     @Override
196     public Class<?> getClassForPath(final List<QName> names) {
197         final DataSchemaNode node = getSchemaNode(names);
198         final SchemaPath path = node.getPath();
199         final Type t = pathToType.get(path);
200
201         final Type type;
202         if (t != null) {
203             type = new ReferencedTypeImpl(t.getPackageName(), t.getName());
204         } else {
205             type = pathToInstantiatedType.get(names);
206             Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
207         }
208
209         @SuppressWarnings("rawtypes")
210         final WeakReference<Class> weakRef = typeToClass.get(type);
211         Preconditions.checkState(weakRef != null, "Could not find loaded class for path: %s and type: %s", path,
212                 type.getFullyQualifiedName());
213         return weakRef.get();
214     }
215
216     @Override
217     public void putPathToClass(final List<QName> names, final Class<?> cls) {
218         final Type reference = Types.typeForClass(cls);
219         pathToInstantiatedType.put(names, reference);
220         LOG.trace("Path {} attached to class {} reference {}", names, cls, reference);
221         bindingClassEncountered(cls);
222     }
223
224     @Override
225     public IdentifierCodec<?> getKeyCodecForPath(final List<QName> names) {
226         @SuppressWarnings("unchecked")
227         Class<? extends Identifiable<?>> cls = (Class<? extends Identifiable<?>>) getClassForPath(names);
228         return getIdentifierCodecForIdentifiable(cls);
229     }
230
231     @Override
232     public <T extends DataContainer> DataContainerCodec<T> getCodecForDataObject(final Class<T> type) {
233         @SuppressWarnings("unchecked")
234         DataContainerCodec<T> ret = (DataContainerCodec<T>) containerCodecs.get(type);
235         if (ret != null) {
236             return ret;
237         }
238         Class<? extends BindingCodec<Map<QName, Object>, Object>> newType = generator.transformerFor(type);
239         BindingCodec<Map<QName, Object>, Object> rawCodec = newInstanceOf(newType);
240         DataContainerCodecImpl<T> newWrapper = new DataContainerCodecImpl<>(rawCodec);
241         containerCodecs.put(type, newWrapper);
242         return newWrapper;
243     }
244
245     @Override
246     @SuppressWarnings("rawtypes")
247     public void bindingClassEncountered(final Class cls) {
248
249         ConcreteType typeRef = Types.typeForClass(cls);
250         if (typeToClass.containsKey(typeRef)) {
251             return;
252         }
253         LOG.trace("Binding Class {} encountered.", cls);
254         WeakReference<Class> weakRef = new WeakReference<>(cls);
255         typeToClass.put(typeRef, weakRef);
256         if (Augmentation.class.isAssignableFrom(cls)) {
257
258         } else if (DataObject.class.isAssignableFrom(cls)) {
259             getCodecForDataObject((Class<? extends DataObject>) cls);
260         }
261     }
262
263     @Override
264     public void onClassProcessed(final Class<?> cls) {
265         ConcreteType typeRef = Types.typeForClass(cls);
266         if (typeToClass.containsKey(typeRef)) {
267             return;
268         }
269         LOG.trace("Binding Class {} encountered.", cls);
270         @SuppressWarnings("rawtypes")
271         WeakReference<Class> weakRef = new WeakReference<Class>(cls);
272         typeToClass.put(typeRef, weakRef);
273     }
274
275     private DataSchemaNode getSchemaNode(final List<QName> path) {
276         QName firstNode = path.get(0);
277         DataNodeContainer previous = currentSchema.findModuleByNamespaceAndRevision(firstNode.getNamespace(),
278                 firstNode.getRevision());
279         Preconditions.checkArgument(previous != null, "Failed to find module %s for path %s", firstNode, path);
280
281         Iterator<QName> iterator = path.iterator();
282         while (iterator.hasNext()) {
283             QName arg = iterator.next();
284             DataSchemaNode currentNode = previous.getDataChildByName(arg);
285             if (currentNode == null && previous instanceof DataNodeContainer) {
286                 currentNode = searchInChoices(previous, arg);
287             }
288             if (currentNode instanceof DataNodeContainer) {
289                 previous = (DataNodeContainer) currentNode;
290             } else if (currentNode instanceof LeafSchemaNode || currentNode instanceof LeafListSchemaNode) {
291                 Preconditions.checkState(!iterator.hasNext(), "Path tries to nest inside leaf node.");
292                 return currentNode;
293             }
294         }
295         return (DataSchemaNode) previous;
296     }
297
298     private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
299         Set<DataSchemaNode> children = node.getChildNodes();
300         for (DataSchemaNode child : children) {
301             if (child instanceof ChoiceNode) {
302                 ChoiceNode choiceNode = (ChoiceNode) child;
303                 DataSchemaNode potential = searchInCases(choiceNode, arg);
304                 if (potential != null) {
305                     return potential;
306                 }
307             }
308         }
309         return null;
310     }
311
312     private DataSchemaNode searchInCases(final ChoiceNode choiceNode, final QName arg) {
313         Set<ChoiceCaseNode> cases = choiceNode.getCases();
314         for (ChoiceCaseNode caseNode : cases) {
315             DataSchemaNode node = caseNode.getDataChildByName(arg);
316             if (node != null) {
317                 return node;
318             }
319         }
320         return null;
321     }
322
323     private static <T> T newInstanceOf(final Class<?> cls) {
324         try {
325             @SuppressWarnings("unchecked")
326             T ret = (T) cls.newInstance();
327             return ret;
328         } catch (InstantiationException e) {
329             LOG.error("Failed to instantiate codec {}", cls.getSimpleName(), e);
330             throw new IllegalStateException(String.format("Failed to instantiate codec %s", cls), e);
331         } catch (IllegalAccessException e) {
332             LOG.debug(
333                     "Run-time consistency issue: constructor for {} is not available. This indicates either a code generation bug or a misconfiguration of JVM.",
334                     cls.getSimpleName(), e);
335             throw new IllegalStateException(String.format("Cannot access contructor of %s", cls), e);
336         }
337     }
338
339     @Override
340     public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class<T> type) {
341         IdentifierCodec<?> obj = identifierCodecs.get(type);
342         if (obj != null) {
343             return obj;
344         }
345         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
346                 .keyTransformerForIdentifiable(type);
347         BindingCodec<Map<QName, Object>, Object> newInstance;
348         newInstance = newInstanceOf(newCodec);
349         IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
350         identifierCodecs.put(type, newWrapper);
351         return newWrapper;
352     }
353
354     @Override
355     public IdentityCodec<?> getIdentityCodec() {
356         return identityRefCodec;
357     }
358
359     @SuppressWarnings("unchecked")
360     @Override
361     public <T extends BaseIdentity> IdentityCodec<T> getCodecForIdentity(final Class<T> codec) {
362         bindingClassEncountered(codec);
363         return identityRefCodec;
364     }
365
366     @Override
367     public void onCodecCreated(final Class<?> cls) {
368         CodecMapping.setIdentifierCodec(cls, instanceIdentifierCodec);
369         CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
370     }
371
372     @Override
373     public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> object) {
374         @SuppressWarnings("unchecked")
375         IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
376         if (obj != null) {
377             return obj;
378         }
379         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
380                 .keyTransformerForIdentifier(object);
381         BindingCodec<Map<QName, Object>, Object> newInstance;
382         newInstance = newInstanceOf(newCodec);
383         IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
384         identifierCodecs.put(object, newWrapper);
385         return newWrapper;
386     }
387
388     @SuppressWarnings("rawtypes")
389     public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
390         ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
391         if (potential != null) {
392             return potential;
393         }
394         ConcreteType typeref = Types.typeForClass(caseClass);
395         ChoiceCaseNode caseSchema = caseTypeToCaseSchema.get(typeref);
396
397         Preconditions.checkState(caseSchema != null, "Case schema is not available for %s", caseClass.getName());
398         Class<? extends BindingCodec> newCodec = generator.caseCodecFor(caseClass, caseSchema);
399         BindingCodec newInstance = newInstanceOf(newCodec);
400         @SuppressWarnings("unchecked")
401         ChoiceCaseCodecImpl caseCodec = new ChoiceCaseCodecImpl(caseClass, caseSchema, newInstance);
402         caseCodecs.put(caseClass, caseCodec);
403         return caseCodec;
404     }
405
406     public void onModuleContextAdded(final SchemaContext schemaContext, final Module module, final ModuleContext context) {
407         pathToType.putAll(context.getChildNodes());
408
409         BiMap<Type, AugmentationSchema> bimap = context.getTypeToAugmentation();
410         for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
411             Type key = entry.getKey();
412             AugmentationSchema value = entry.getValue();
413             Set<DataSchemaNode> augmentedNodes = value.getChildNodes();
414             if (augmentedNodes != null && !(augmentedNodes.isEmpty())) {
415                 typeToAugment.put(key, value);
416             }
417         }
418
419         qnamesToIdentityMap.putAll(context.getIdentities());
420         for (Entry<QName, GeneratedTOBuilder> identity : context.getIdentities().entrySet()) {
421             typeToQname.put(
422                     new ReferencedTypeImpl(identity.getValue().getPackageName(), identity.getValue().getName()),
423                     identity.getKey());
424         }
425
426         synchronized (augmentableToAugmentations) {
427             augmentableToAugmentations.putAll(context.getAugmentableToAugmentations());
428         }
429         synchronized (choiceToCases) {
430             choiceToCases.putAll(context.getChoiceToCases());
431         }
432         synchronized (caseTypeToCaseSchema) {
433             caseTypeToCaseSchema.putAll(context.getCaseTypeToSchemas());
434         }
435     }
436
437     @Override
438     public void onGlobalContextUpdated(final SchemaContext context) {
439         currentSchema = context;
440         resetDispatchCodecsAdaptation();
441
442     }
443
444     /**
445      * Resets / clears adaptation for all schema context sensitive codecs in
446      * order for them to adapt to new schema context and maybe newly discovered
447      * augmentations This ensure correct behaviour for augmentations and
448      * augmented cases for preexisting codecs, which augmentations were
449      * introduced at later point in time.
450      *
451      * This also makes removed augmentations unavailable.
452      */
453     private void resetDispatchCodecsAdaptation() {
454         synchronized (dispatchCodecs) {
455             for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
456                 codec.resetCodec(this);
457             }
458         }
459     }
460
461     @SuppressWarnings({ "unchecked", "rawtypes" })
462     @Override
463     public void onChoiceCodecCreated(final Class<?> choiceClass,
464             final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec, final ChoiceNode schema) {
465         ChoiceCodec<?> oldCodec = choiceCodecs.get(choiceClass);
466         Preconditions.checkState(oldCodec == null);
467         BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
468         PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
469         DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass,this);
470         choiceCodecs.put(choiceClass, newCodec);
471         synchronized (dispatchCodecs) {
472             dispatchCodecs.put(choiceClass, dispatchCodec);
473         }
474         CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
475     }
476
477     @Override
478     public void onValueCodecCreated(final Class<?> valueClass, final Class<?> valueCodec) {
479     }
480
481     @Override
482     public void onCaseCodecCreated(final Class<?> choiceClass,
483             final Class<? extends BindingCodec<Map<QName, Object>, Object>> choiceCodec) {
484     }
485
486     @Override
487     public void onDataContainerCodecCreated(final Class<?> dataClass,
488             final Class<? extends BindingCodec<?, ?>> dataCodec) {
489         if (Augmentable.class.isAssignableFrom(dataClass)) {
490             AugmentableDispatchCodec augmentableCodec = getAugmentableCodec(dataClass);
491             CodecMapping.setAugmentationCodec(dataCodec, augmentableCodec);
492         }
493     }
494
495     public synchronized AugmentableDispatchCodec getAugmentableCodec(final Class<?> dataClass) {
496         AugmentableDispatchCodec ret = augmentableCodecs.get(dataClass);
497         if (ret != null) {
498             return ret;
499         }
500         ret = new AugmentableDispatchCodec(dataClass,this);
501         augmentableCodecs.put(dataClass, ret);
502         synchronized (dispatchCodecs) {
503             dispatchCodecs.put(dataClass, ret);
504         }
505         ret.tryToLoadImplementations();
506         return ret;
507     }
508
509     private static abstract class IntermediateCodec<T> implements //
510             DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
511
512         private final BindingCodec<Map<QName, Object>, Object> delegate;
513
514         @Override
515         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
516             return delegate;
517         }
518
519         public IntermediateCodec(final BindingCodec<Map<QName, Object>, Object> delegate) {
520             this.delegate = delegate;
521         }
522
523         @Override
524         public Node<?> serialize(final ValueWithQName<T> input) {
525             Map<QName, Object> intermediateOutput = delegate.serialize(input);
526             return IntermediateMapping.toNode(intermediateOutput);
527         }
528
529     }
530
531     private static class IdentifierCodecImpl<T extends Identifier<?>> //
532             extends IntermediateCodec<T> //
533             implements IdentifierCodec<T> {
534
535         public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
536             super(delegate);
537         }
538
539         @Override
540         public ValueWithQName<T> deserialize(final Node<?> input) {
541             QName qname = input.getNodeType();
542             @SuppressWarnings("unchecked")
543             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
544             return new ValueWithQName<T>(qname, value);
545         }
546
547         @Override
548         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
549             QName qname = input.getNodeType();
550             @SuppressWarnings("unchecked")
551             T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
552             return new ValueWithQName<T>(qname, value);
553         }
554
555         @Override
556         public CompositeNode serialize(final ValueWithQName<T> input) {
557             return (CompositeNode) super.serialize(input);
558         }
559     }
560
561     private static class DataContainerCodecImpl<T extends DataContainer> //
562             extends IntermediateCodec<T> //
563             implements DataContainerCodec<T> {
564
565         public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
566             super(delegate);
567         }
568
569         @Override
570         public ValueWithQName<T> deserialize(final Node<?> input) {
571             if (input == null) {
572                 return null;
573             }
574             QName qname = input.getNodeType();
575             @SuppressWarnings("unchecked")
576             T value = (T) getDelegate().deserialize((Map<QName, Object>) input);
577             return new ValueWithQName<T>(qname, value);
578         }
579
580         @Override
581         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
582             if (input == null) {
583                 return null;
584             }
585             QName qname = input.getNodeType();
586             @SuppressWarnings("unchecked")
587             T value = (T) getDelegate().deserialize((Map<QName, Object>) input, bindingIdentifier);
588             return new ValueWithQName<T>(qname, value);
589         }
590
591         @Override
592         public CompositeNode serialize(final ValueWithQName<T> input) {
593             return (CompositeNode) super.serialize(input);
594         }
595     }
596
597     private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
598
599         boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
600
601         public Class<?> getDataType();
602
603     }
604
605     @SuppressWarnings("rawtypes")
606     private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
607
608         private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
609         private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
610         private LazyGeneratedCodecRegistry registry;
611
612
613         protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
614             this.registry = registry;
615         }
616
617         protected Map<Class, T> getImplementations() {
618             return implementations;
619         }
620
621         /**
622          * Resets codec adaptation based on location and schema context.
623          *
624          * This is required if new cases / augmentations were introduced or
625          * removed and first use of codec is triggered by invocation from DOM to
626          * Java, so the implementations may change and this may require loading
627          * of new codecs and/or removal of existing ones.
628          *
629          */
630         public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
631             registry = currentRegistry;
632             adaptedForPaths.clear();
633             resetAdaptationImpl();
634         }
635
636         protected void resetAdaptationImpl() {
637             // Intentionally NOOP, subclasses may specify their custom
638             // behaviour.
639         }
640
641         protected final LazyGeneratedCodecRegistry getRegistry() {
642             return registry;
643         }
644         protected void addImplementation(final T implementation) {
645             implementations.put(implementation.getDataType(), implementation);
646         }
647
648         @Override
649         public final Object deserialize(final Object input) {
650             throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
651         }
652
653         @Override
654         public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
655             adaptForPath(parentPath);
656             Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
657             CompositeNode parentData = (CompositeNode) parent;
658             ArrayList<T> applicable = new ArrayList<>(implementations.size());
659
660             /*
661              * Codecs are filtered to only ones, which
662              * are applicable in supplied parent context.
663              *
664              */
665             for (T impl : getImplementations().values()) {
666                 @SuppressWarnings("unchecked")
667                 boolean codecApplicable = impl.isApplicable(parentPath, parentData);
668                 if (codecApplicable) {
669                     applicable.add(impl);
670                 }
671             }
672             LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",this,parent,parentPath,applicable,getImplementations().values());
673
674             /* In case of none is applicable, we return
675              * null. Since there is no mixin which
676              * is applicable in this location.
677             */
678             if(applicable.isEmpty()) {
679                 return null;
680             }
681             return deserializeImpl(parentData, parentPath, applicable);
682         }
683
684         protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
685                 Iterable<T> applicableCodecs);
686
687         @Override
688         public Object serialize(final Object input) {
689             Preconditions.checkArgument(input instanceof DataContainer);
690             Class<? extends DataContainer> inputType = ((DataContainer) input).getImplementedInterface();
691             T implementation = implementations.get(inputType);
692             if (implementation == null) {
693                 implementation = tryToLoadImplementationImpl(inputType);
694             }
695
696             return null;
697         }
698
699         private T tryToLoadImplementationImpl(final Class<? extends DataContainer> inputType) {
700             T implementation = tryToLoadImplementation(inputType);
701             Preconditions.checkArgument(implementation != null, "Data type %s is not supported.", inputType);
702             addImplementation(implementation);
703             return implementation;
704         }
705
706         protected final synchronized void adaptForPath(final InstanceIdentifier<?> path) {
707             if (adaptedForPaths.contains(path)) {
708                 return;
709             }
710             LOG.debug("Adapting mixin codec {} for path {}",this,path);
711             /**
712              * We search in schema context if the use of this location aware
713              * codec (augmentable codec, case codec) makes sense on provided
714              * location (path)
715              *
716              */
717             Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(getRegistry().currentSchema,
718                     path);
719             /**
720              * If context node is present, this codec makes sense on provided
721              * location.
722              *
723              */
724             if (contextNode.isPresent()) {
725                 synchronized (this) {
726                     /**
727                      *
728                      * We adapt (turn on / off) possible implementations of
729                      * child codecs (augmentations, cases) based on this
730                      * location.
731                      *
732                      *
733                      */
734
735                     adaptForPathImpl(path, contextNode.get());
736                     try {
737                         /**
738                          * We trigger serialization of instance identifier, to
739                          * make sure instance identifier codec is aware of
740                          * combination of this path / augmentation / case
741                          */
742                         getRegistry().getInstanceIdentifierCodec().serialize(path);
743                     } catch (Exception e) {
744                         LOG.warn("Exception during preparation of instance identifier codec for  path {}.", path, e);
745                     }
746                     adaptedForPaths.add(path);
747                 }
748             } else {
749                 LOG.debug("Context node (parent node) not found for {}", path);
750             }
751         }
752
753         protected abstract T tryToLoadImplementation(Class<? extends DataContainer> inputType);
754
755         protected abstract void tryToLoadImplementations();
756
757         protected abstract void adaptForPathImpl(InstanceIdentifier<?> path, DataNodeContainer ctx);
758     }
759
760     @SuppressWarnings("rawtypes")
761     private static class ChoiceCaseCodecImpl<T extends DataContainer> implements ChoiceCaseCodec<T>, //
762             Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
763         private final BindingCodec delegate;
764         private final ChoiceCaseNode schema;
765         private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
766         private final Class<?> dataType;
767
768         public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
769                 final BindingCodec newInstance) {
770             this.delegate = newInstance;
771             this.dataType = caseClass;
772             this.schema = caseNode;
773             instantiatedLocations = new HashMap<>();
774         }
775
776         @Override
777         public ValueWithQName<T> deserialize(final Node<?> input) {
778             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
779         }
780
781         @Override
782         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
783             if (input == null) {
784                 return null;
785             }
786             QName qname = input.getNodeType();
787             synchronized (instantiatedLocations) {
788                 ChoiceCaseNode instantiation = instantiatedLocations.get(bindingIdentifier);
789                 if (instantiation != null) {
790                     qname = instantiatedLocations.get(bindingIdentifier).getQName();
791                 }
792             }
793             @SuppressWarnings("unchecked")
794             T value = (T) getDelegate().deserialize(new SimpleEntry(qname, input), bindingIdentifier);
795             return new ValueWithQName<T>(qname, value);
796         }
797
798         @Override
799         public CompositeNode serialize(final ValueWithQName<T> input) {
800             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
801         }
802
803         @Override
804         public BindingCodec getDelegate() {
805             return delegate;
806         }
807
808         public ChoiceCaseNode getSchema() {
809             return schema;
810         }
811
812         @Override
813         @Deprecated
814         public boolean isAcceptable(final Node<?> input) {
815             return checkAgainstSchema(schema, input);
816         }
817
818         private static boolean checkAgainstSchema(final ChoiceCaseNode schema, final Node<?> node) {
819             if (node instanceof CompositeNode) {
820                 CompositeNode input = (CompositeNode) node;
821                 for (Node<?> childNode : input.getValue()) {
822                     QName child = childNode.getNodeType();
823                     if (schema.getDataChildByName(child) != null) {
824                         return true;
825                     }
826                 }
827             }
828             return false;
829         }
830
831         @Override
832         public Class<?> getDataType() {
833             return dataType;
834         }
835
836         public void adaptForPath(final InstanceIdentifier<?> augTarget, final ChoiceCaseNode choiceCaseNode) {
837             synchronized (instantiatedLocations) {
838                 instantiatedLocations.put(augTarget, choiceCaseNode);
839             }
840         }
841
842         @Override
843         public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
844             ChoiceCaseNode instantiatedSchema = null;
845             synchronized (instantiatedLocations) {
846                 instantiatedSchema = instantiatedLocations.get(path);
847             }
848             if (instantiatedSchema == null) {
849                 return false;
850             }
851             return checkAgainstSchema(instantiatedSchema, input);
852         }
853
854         protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
855             if (schema.isAugmenting()) {
856                 return true;
857             }
858             // Choice QName
859             QName parentQName = Iterables.get(schema.getPath().getPathTowardsRoot(), 1);
860             if (!parentQName.getNamespace().equals(schema.getQName().getNamespace())) {
861                 return true;
862             }
863             if (!parentQName.equals(choiceName)) {
864                 // This item is instantiation of choice via uses in other YANG
865                 // module
866                 if (choiceName.getNamespace().equals(schema.getQName())) {
867                     // Original definition of grouping is in same namespace
868                     // as original definition of case
869                     // so for sure case is introduced via instantiation of
870                     // grouping
871                     return false;
872                 }
873                 // Since we are still here, that means case has same namespace
874                 // as its parent, which is instantiation of grouping
875                 // but case namespace is different from parent node
876                 // so it is augmentation.
877                 return true;
878             }
879             return false;
880         }
881
882         @Override
883         public String toString() {
884             return "ChoiceCaseCodec [case=" + dataType
885                     + ", knownLocations=" + instantiatedLocations.keySet() + "]";
886         }
887     }
888
889     private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
890             Delegator<BindingCodec<Map<QName, Object>, Object>> {
891
892         private final BindingCodec<Map<QName, Object>, Object> delegate;
893
894         public PublicChoiceCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
895             this.delegate = delegate;
896         }
897
898         @Override
899         public ValueWithQName<T> deserialize(final Node<?> input) {
900             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
901         }
902
903         @Override
904         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
905             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
906         }
907
908         @Override
909         public Node<?> serialize(final ValueWithQName<T> input) {
910             throw new UnsupportedOperationException("Direct invocation of this codec is not allowed.");
911         }
912
913         @Override
914         public BindingCodec<Map<QName, Object>, Object> getDelegate() {
915             return delegate;
916         }
917
918     }
919
920     class DispatchChoiceCodecImpl extends LocationAwareDispatchCodec<ChoiceCaseCodecImpl<?>> {
921         private final Class<?> choiceType;
922         private final QName choiceName;
923
924         private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
925             super(registry);
926             choiceType = type;
927             choiceName = BindingReflections.findQName(type);
928         }
929
930         @Override
931         public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
932                 final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
933             ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
934             ValueWithQName<?> value = caseCodec.deserialize(input, path);
935             if (value != null) {
936                 return value.getValue();
937             }
938             return null;
939         }
940
941         @SuppressWarnings("unchecked")
942         @Override
943         public Object serialize(final Object input) {
944             Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
945             @SuppressWarnings("rawtypes")
946             QName derivedQName = (QName) ((Map.Entry) input).getKey();
947             @SuppressWarnings("rawtypes")
948             Object inputValue = ((Map.Entry) input).getValue();
949             Preconditions.checkArgument(inputValue instanceof DataObject);
950             Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
951             ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
952             Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
953             if (codec.isAugmenting(choiceName, derivedQName)) {
954                 // If choice is augmenting we use QName which defined this
955                 // augmentation
956                 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
957             }
958             return codec.getDelegate().serialize(input);
959         }
960
961         @SuppressWarnings("rawtypes")
962         protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
963             try {
964                 @SuppressWarnings("unchecked")
965                 Class<? extends DataContainer> clazz = (Class<? extends DataContainer>) classLoadingStrategy
966                         .loadClass(potential);
967                 ChoiceCaseCodecImpl codec = tryToLoadImplementation(clazz);
968                 addImplementation(codec);
969                 return Optional.of(codec);
970             } catch (ClassNotFoundException e) {
971                 LOG.warn("Failed to find class for choice {}", potential, e);
972             }
973             return Optional.absent();
974         }
975
976         @Override
977         protected ChoiceCaseCodecImpl<?> tryToLoadImplementation(final Class<? extends DataContainer> inputType) {
978             ChoiceCaseCodecImpl<?> codec = getCaseCodecFor(inputType);
979             addImplementation(codec);
980             return codec;
981         }
982
983         @Override
984         protected void tryToLoadImplementations() {
985             Type type = referencedType(choiceType);
986             Collection<Type> potentialCases;
987             synchronized (choiceToCases) {
988                 potentialCases = choiceToCases.get(type);
989             }
990             for (Type potential : potentialCases) {
991                 try {
992                     tryToLoadImplementation(potential);
993                 } catch (CodeGenerationException e) {
994                     LOG.warn("Failed to proactively generate choice code for {}", type, e);
995                 }
996             }
997         }
998
999         @Override
1000         protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1001             Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
1002             tryToLoadImplementations();
1003             Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
1004             for (@SuppressWarnings("rawtypes")
1005             Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
1006                 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
1007                 Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(newChoice.get(),
1008                         caseCodec.getSchema());
1009                 if (instantiatedSchema.isPresent()) {
1010                     caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
1011                 }
1012             }
1013         }
1014
1015
1016
1017         @Override
1018         public String toString() {
1019             return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
1020         }
1021     }
1022
1023     @SuppressWarnings({ "rawtypes", "unchecked" })
1024     static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
1025
1026         private final Class augmentableType;
1027
1028         public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
1029             super(registry);
1030             Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
1031             augmentableType = type;
1032         }
1033
1034         @Override
1035         // TODO deprecate use without iid
1036         public Object serialize(final Object input) {
1037             if (input instanceof Augmentable<?>) {
1038                 Map<Class, Augmentation> augmentations = getAugmentations(input);
1039                 return serializeImpl(augmentations);
1040             }
1041             return null;
1042         }
1043
1044         private Map<Class, Augmentation> getAugmentations(final Object input) {
1045             Field augmentationField;
1046             try {
1047                 augmentationField = input.getClass().getDeclaredField("augmentation");
1048                 augmentationField.setAccessible(true);
1049                 Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
1050                 return augMap;
1051             } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
1052                 LOG.debug("Could not read augmentations for {}", input, e);
1053             }
1054             return Collections.emptyMap();
1055         }
1056
1057         @SuppressWarnings("deprecation")
1058         private List serializeImpl(final Map<Class, Augmentation> input) {
1059             List ret = new ArrayList<>();
1060             for (Entry<Class, Augmentation> entry : input.entrySet()) {
1061                 AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
1062                 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
1063                 ret.addAll(node.getChildren());
1064             }
1065             return ret;
1066         }
1067
1068         @Override
1069         public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
1070                 final Iterable<AugmentationCodecWrapper> codecs) {
1071             LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}",this,input,path,codecs);
1072             Map<Class, Augmentation> ret = new HashMap<>();
1073             for (AugmentationCodecWrapper codec : codecs) {
1074                     // We add Augmentation Identifier to path, in order to
1075                     // correctly identify children.
1076                     Class type = codec.getDataType();
1077                     final InstanceIdentifier augmentPath = path.augmentation(type);
1078                     ValueWithQName<?> value = codec.deserialize(input, augmentPath);
1079                     if (value != null && value.getValue() != null) {
1080                         ret.put(type, (Augmentation) value.getValue());
1081                     }
1082             }
1083             return ret;
1084         }
1085
1086         protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
1087             try {
1088                 Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
1089                         .loadClass(potential);
1090                 return Optional.of(tryToLoadImplementation(clazz));
1091             } catch (ClassNotFoundException e) {
1092                 LOG.warn("Failed to find class for augmentation of {}", potential, e);
1093             }
1094             return Optional.absent();
1095         }
1096
1097         @Override
1098         protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
1099             AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(inputType);
1100             addImplementation(potentialImpl);
1101             return potentialImpl;
1102         }
1103
1104         @Override
1105         protected void tryToLoadImplementations() {
1106             Type type = referencedType(augmentableType);
1107             Collection<Type> potentialAugmentations;
1108             synchronized (augmentableToAugmentations) {
1109                 potentialAugmentations = new ArrayList(augmentableToAugmentations.get(type));
1110             }
1111             for (Type potential : potentialAugmentations) {
1112                 try {
1113                     tryToLoadImplementation(potential);
1114                 } catch (CodeGenerationException e) {
1115                     LOG.warn("Failed to proactively generate augment code for {}", type, e);
1116                 }
1117             }
1118         }
1119
1120         @Override
1121         protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
1122             if (ctxNode instanceof AugmentationTarget) {
1123                 Set<AugmentationSchema> availableAugmentations = ((AugmentationTarget) ctxNode)
1124                         .getAvailableAugmentations();
1125                 if (!availableAugmentations.isEmpty()) {
1126                     updateAugmentationMapping(augTarget, availableAugmentations);
1127                 }
1128             }
1129         }
1130
1131         /**
1132          *
1133          * Adapts augmentation codec for specific provider location (target)
1134          *
1135          * Since augmentation are not forward-referencing and may be discovered
1136          * during runtime, we need to adapt {@link AugmentableDispatchCodec},
1137          * {@link AugmentationCodecWrapper} and {@link InstanceIdentifierCodec}
1138          * for this newly discovered location where augmentation may be used.
1139          *
1140          * Adaptation consists of:
1141          * <ol>
1142          * <li>scan of available (valid) augmentations for current location
1143          * <li>lookup for Java classes derived from this augmentations
1144          * <li>generation of missing codecs
1145          * <li>updating Augmentation codecs to work with new location
1146          * <li>updating Instance Identifier to work with new location
1147          *
1148          */
1149         private void updateAugmentationMapping(final InstanceIdentifier<?> augTarget,
1150                 final Set<AugmentationSchema> availableAugmentations) {
1151             for (AugmentationSchema aug : availableAugmentations) {
1152
1153                 Type potentialType = getTypeForAugmentation(aug);
1154                 if (potentialType != null) {
1155                     Optional<AugmentationCodecWrapper> potentialImpl = tryToLoadImplementation(potentialType);
1156                     if (potentialImpl.isPresent()) {
1157                         potentialImpl.get().addApplicableFor(augTarget, aug);
1158                         Class augType = potentialImpl.get().getDataType();
1159                         InstanceIdentifier augPath = augTarget.augmentation(augType);
1160                         try {
1161
1162                             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = getRegistry().getInstanceIdentifierCodec()
1163                                     .serialize(augPath);
1164                             if (domPath == null) {
1165                                 LOG.error("Unable to serialize instance identifier for {}", augPath);
1166                             }
1167                         } catch (Exception e) {
1168                             LOG.error("Unable to serialize instance identifiers for {}", augPath, e);
1169                         }
1170
1171                     }
1172                 } else {
1173                     // Omits warning for empty augmentations since they are not
1174                     // represented in data
1175                     if (!aug.getChildNodes().isEmpty()) {
1176                         LOG.warn("Could not find generated type for augmentation {} with children {}", aug,
1177                                 aug.getChildNodes());
1178                     }
1179                 }
1180             }
1181         }
1182
1183         private Type getTypeForAugmentation(final AugmentationSchema aug) {
1184             Optional<AugmentationSchema> currentAug = Optional.of(aug);
1185             while (currentAug.isPresent()) {
1186                 Type potentialType = typeToAugment.inverse().get(currentAug.get());
1187                 if (potentialType != null) {
1188                     return potentialType;
1189                 }
1190                 currentAug = currentAug.get().getOriginalDefinition();
1191             }
1192             return null;
1193         }
1194
1195         @Override
1196         public String toString() {
1197             return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
1198         }
1199
1200     }
1201
1202     @SuppressWarnings("rawtypes")
1203     private static class AugmentationCodecWrapper<T extends Augmentation<?>> implements AugmentationCodec<T>,
1204             Delegator<BindingCodec>, LocationAwareBindingCodec<Node<?>, ValueWithQName<T>> {
1205
1206         private final BindingCodec delegate;
1207         private final QName augmentationQName;
1208         private final Multimap<InstanceIdentifier<?>, QName> validAugmentationTargets;
1209         private final Class<?> augmentationType;
1210
1211         public AugmentationCodecWrapper(final BindingCodec<Map<QName, Object>, Object> rawCodec, final Class<?> dataType) {
1212             this.delegate = rawCodec;
1213             this.augmentationType = dataType;
1214             this.augmentationQName = BindingReflections.findQName(rawCodec.getClass());
1215             this.validAugmentationTargets = Multimaps.synchronizedSetMultimap(HashMultimap
1216                     .<InstanceIdentifier<?>, QName> create());
1217         }
1218
1219         public void addApplicableFor(final InstanceIdentifier<?> path, final AugmentationSchema aug) {
1220             for (DataSchemaNode child : aug.getChildNodes()) {
1221                 validAugmentationTargets.put(path, child.getQName());
1222             }
1223         }
1224
1225         @Override
1226         public BindingCodec getDelegate() {
1227             return delegate;
1228         }
1229
1230         @Override
1231         public CompositeNode serialize(final ValueWithQName<T> input) {
1232             @SuppressWarnings("unchecked")
1233             List<Map<QName, Object>> rawValues = (List<Map<QName, Object>>) getDelegate().serialize(input);
1234             List<Node<?>> serialized = new ArrayList<>(rawValues.size());
1235             for (Map<QName, Object> val : rawValues) {
1236                 serialized.add(IntermediateMapping.toNode(val));
1237             }
1238             return new CompositeNodeTOImpl(input.getQname(), null, serialized);
1239         }
1240
1241         @Override
1242         @SuppressWarnings("unchecked")
1243         public ValueWithQName<T> deserialize(final Node<?> input) {
1244             Object rawCodecValue = getDelegate().deserialize(input);
1245             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1246         }
1247
1248         @Override
1249         @SuppressWarnings("unchecked")
1250         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
1251             Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
1252             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
1253         }
1254
1255         @Override
1256         public QName getAugmentationQName() {
1257             return augmentationQName;
1258         }
1259
1260         @Override
1261         public boolean isAcceptable(final InstanceIdentifier<?> path) {
1262             if (path == null) {
1263                 return false;
1264             }
1265             return validAugmentationTargets.containsKey(path);
1266         }
1267
1268         @Override
1269         public boolean isApplicable(final InstanceIdentifier parentPath,final CompositeNode parentData) {
1270             return isAcceptable(parentPath);
1271         }
1272
1273         @Override
1274         public Class<?> getDataType() {
1275             return augmentationType;
1276         }
1277
1278         @Override
1279         public String toString() {
1280             return "AugmentationCodecWrapper [augmentation=" + augmentationType
1281                     + ", knownLocations=" + validAugmentationTargets.keySet() + "]";
1282         }
1283     }
1284
1285     @SuppressWarnings("rawtypes")
1286     private class IdentityCompositeCodec implements IdentityCodec {
1287
1288         @Override
1289         public Object deserialize(final Object input) {
1290             Preconditions.checkArgument(input instanceof QName);
1291             return deserialize((QName) input);
1292         }
1293
1294         @Override
1295         public Class<?> deserialize(final QName input) {
1296             if(input == null) {
1297                 return null;
1298             }
1299             Type type = qnamesToIdentityMap.get(input);
1300             if (type == null) {
1301                 String packageName = BindingMapping.getRootPackageName(input);
1302                 String className = BindingMapping.getClassName(input);
1303                 type = new ReferencedTypeImpl(packageName, className);
1304             }
1305             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1306             WeakReference<Class> softref = typeToClass.get(typeref);
1307             if (softref == null) {
1308
1309                 try {
1310                     Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1311                     if (cls != null) {
1312                         serialize(cls);
1313                         return cls;
1314                     }
1315                 } catch (Exception e) {
1316                     LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1317                             typeref.getFullyQualifiedName());
1318                 }
1319                 return null;
1320             }
1321             return softref.get();
1322         }
1323
1324         @Override
1325         public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
1326             Type type = qnamesToIdentityMap.get(input);
1327             if (type == null) {
1328                 throw new IllegalArgumentException( "Invalid for \"" + input + "\"." );
1329             }
1330             ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
1331             WeakReference<Class> softref = typeToClass.get(typeref);
1332             if (softref == null) {
1333
1334                 try {
1335                     Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
1336                     if (cls != null) {
1337                         serialize(cls);
1338                         return cls;
1339                     }
1340                 } catch (Exception e) {
1341                     LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
1342                             typeref.getFullyQualifiedName());
1343                 }
1344                 return null;
1345             }
1346             return softref.get();
1347         }
1348
1349         @Override
1350         public QName serialize(final Class input) {
1351             Preconditions.checkArgument(BaseIdentity.class.isAssignableFrom(input));
1352             bindingClassEncountered(input);
1353             QName qname = identityQNames.get(input);
1354             if (qname != null) {
1355                 return qname;
1356             }
1357             qname = BindingReflections.findQName(input);
1358             if (qname != null) {
1359                 identityQNames.put(input, qname);
1360             }
1361             return qname;
1362         }
1363
1364         @Override
1365         public Object serialize(final Object input) {
1366             Preconditions.checkArgument(input instanceof Class);
1367             return serialize((Class) input);
1368         }
1369
1370     }
1371
1372     private static final Type referencedType(final Class<?> augmentableType) {
1373         return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());
1374     }
1375 }