BUG-576: fixed invalid if conditions in LazyGeneratedCodecRegistry.
[yangtools.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / generator / impl / LazyGeneratedCodecRegistry.java
index f857c0d7315adaf4d9e9704cb601513bc8d2887a..f72856e1c11b540c2c6d855ef26b0ab7455a209e 100644 (file)
@@ -7,8 +7,14 @@
  */
 package org.opendaylight.yangtools.sal.binding.generator.impl;
 
-import java.lang.ref.WeakReference;
-import java.lang.reflect.Field;
+import com.google.common.base.Optional;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.BiMap;
+import com.google.common.collect.HashBiMap;
+import com.google.common.collect.HashMultimap;
+import com.google.common.collect.Iterables;
+import com.google.common.collect.Multimap;
+import com.google.common.collect.Multimaps;
 import java.util.AbstractMap.SimpleEntry;
 import java.util.ArrayList;
 import java.util.Collection;
@@ -23,7 +29,6 @@ import java.util.Set;
 import java.util.WeakHashMap;
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
-
 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
 import org.opendaylight.yangtools.binding.generator.util.Types;
 import org.opendaylight.yangtools.concepts.Delegator;
@@ -37,11 +42,13 @@ import org.opendaylight.yangtools.yang.binding.Augmentable;
 import org.opendaylight.yangtools.yang.binding.Augmentation;
 import org.opendaylight.yangtools.yang.binding.BaseIdentity;
 import org.opendaylight.yangtools.yang.binding.BindingCodec;
+import org.opendaylight.yangtools.yang.binding.BindingMapping;
 import org.opendaylight.yangtools.yang.binding.DataContainer;
 import org.opendaylight.yangtools.yang.binding.DataObject;
 import org.opendaylight.yangtools.yang.binding.Identifier;
 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
+import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
 import org.opendaylight.yangtools.yang.common.QName;
 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
 import org.opendaylight.yangtools.yang.data.api.Node;
@@ -67,23 +74,13 @@ import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
 import org.opendaylight.yangtools.yang.model.api.Module;
 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
+import org.opendaylight.yangtools.yang.model.api.SchemaNode;
 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
+import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.google.common.base.Optional;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.BiMap;
-import com.google.common.collect.HashBiMap;
-import com.google.common.collect.HashMultimap;
-import com.google.common.collect.Iterables;
-import com.google.common.collect.Multimap;
-import com.google.common.collect.Multimaps;
-
-class LazyGeneratedCodecRegistry implements //
-        CodecRegistry, //
-        SchemaContextListener, //
-        GeneratorListener {
+class LazyGeneratedCodecRegistry implements CodecRegistry, SchemaContextListener, GeneratorListener {
 
     private static final Logger LOG = LoggerFactory.getLogger(LazyGeneratedCodecRegistry.class);
 
@@ -100,12 +97,13 @@ class LazyGeneratedCodecRegistry implements //
             .synchronizedMap(new WeakHashMap<Class<?>, AugmentableDispatchCodec>());
     private static final Map<Class<?>, AugmentationCodecWrapper<?>> augmentationCodecs = Collections
             .synchronizedMap(new WeakHashMap<Class<?>, AugmentationCodecWrapper<?>>());
+
+    private static final Map<Class<?>, LocationAwareDispatchCodec<?>> dispatchCodecs = Collections
+            .synchronizedMap(new WeakHashMap<Class<?>, LocationAwareDispatchCodec<?>>());
+
     private static final Map<Class<?>, QName> identityQNames = Collections
             .synchronizedMap(new WeakHashMap<Class<?>, QName>());
     private static final Map<QName, Type> qnamesToIdentityMap = new ConcurrentHashMap<>();
-    /** Binding type to encountered classes mapping **/
-    @SuppressWarnings("rawtypes")
-    private static final Map<Type, WeakReference<Class>> typeToClass = new ConcurrentHashMap<>();
 
     private static final ConcurrentMap<Type, ChoiceCaseNode> caseTypeToCaseSchema = new ConcurrentHashMap<>();
 
@@ -189,7 +187,12 @@ class LazyGeneratedCodecRegistry implements //
 
     @Override
     public Class<?> getClassForPath(final List<QName> names) {
-        final DataSchemaNode node = getSchemaNode(names);
+        DataSchemaNode node = getSchemaNode(names);
+        Preconditions.checkArgument(node != null, "Path %s points to invalid schema location", names);
+        SchemaNode originalDefinition = SchemaNodeUtils.getRootOriginalIfPossible(node);
+        if (originalDefinition instanceof DataSchemaNode) {
+            node = (DataSchemaNode) originalDefinition;
+        }
         final SchemaPath path = node.getPath();
         final Type t = pathToType.get(path);
 
@@ -201,11 +204,12 @@ class LazyGeneratedCodecRegistry implements //
             Preconditions.checkState(type != null, "Failed to lookup instantiated type for path %s", path);
         }
 
-        @SuppressWarnings("rawtypes")
-        final WeakReference<Class> weakRef = typeToClass.get(type);
-        Preconditions.checkState(weakRef != null, "Could not find loaded class for path: %s and type: %s", path,
-                type.getFullyQualifiedName());
-        return weakRef.get();
+        try {
+            return classLoadingStrategy.loadClass(type);
+        } catch (ClassNotFoundException e) {
+            throw new IllegalStateException(String.format("Could not find loaded class for path: %s and type: %s",
+                    path, type.getFullyQualifiedName()));
+        }
     }
 
     @Override
@@ -240,32 +244,16 @@ class LazyGeneratedCodecRegistry implements //
     @Override
     @SuppressWarnings("rawtypes")
     public void bindingClassEncountered(final Class cls) {
-
-        ConcreteType typeRef = Types.typeForClass(cls);
-        if (typeToClass.containsKey(typeRef)) {
-            return;
-        }
-        LOG.trace("Binding Class {} encountered.", cls);
-        WeakReference<Class> weakRef = new WeakReference<>(cls);
-        typeToClass.put(typeRef, weakRef);
         if (Augmentation.class.isAssignableFrom(cls)) {
-
+            // Intentionally NOOP
         } else if (DataObject.class.isAssignableFrom(cls)) {
-            @SuppressWarnings({ "unchecked", "unused" })
-            Object cdc = getCodecForDataObject((Class<? extends DataObject>) cls);
+            getCodecForDataObject((Class<? extends DataObject>) cls);
         }
     }
 
     @Override
     public void onClassProcessed(final Class<?> cls) {
-        ConcreteType typeRef = Types.typeForClass(cls);
-        if (typeToClass.containsKey(typeRef)) {
-            return;
-        }
-        LOG.trace("Binding Class {} encountered.", cls);
-        @SuppressWarnings("rawtypes")
-        WeakReference<Class> weakRef = new WeakReference<Class>(cls);
-        typeToClass.put(typeRef, weakRef);
+
     }
 
     private DataSchemaNode getSchemaNode(final List<QName> path) {
@@ -278,7 +266,7 @@ class LazyGeneratedCodecRegistry implements //
         while (iterator.hasNext()) {
             QName arg = iterator.next();
             DataSchemaNode currentNode = previous.getDataChildByName(arg);
-            if (currentNode == null && previous instanceof DataNodeContainer) {
+            if (currentNode == null) {
                 currentNode = searchInChoices(previous, arg);
             }
             if (currentNode instanceof DataNodeContainer) {
@@ -292,8 +280,7 @@ class LazyGeneratedCodecRegistry implements //
     }
 
     private DataSchemaNode searchInChoices(final DataNodeContainer node, final QName arg) {
-        Set<DataSchemaNode> children = node.getChildNodes();
-        for (DataSchemaNode child : children) {
+        for (DataSchemaNode child : node.getChildNodes()) {
             if (child instanceof ChoiceNode) {
                 ChoiceNode choiceNode = (ChoiceNode) child;
                 DataSchemaNode potential = searchInCases(choiceNode, arg);
@@ -332,18 +319,39 @@ class LazyGeneratedCodecRegistry implements //
         }
     }
 
+    @SuppressWarnings("unchecked")
     @Override
-    public <T extends Identifiable<?>> IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class<T> type) {
-        IdentifierCodec<?> obj = identifierCodecs.get(type);
+    public IdentifierCodec<?> getIdentifierCodecForIdentifiable(final Class identifiable) {
+
+        Class identifier = ClassLoaderUtils.findFirstGenericArgument(identifiable,
+                org.opendaylight.yangtools.yang.binding.Identifiable.class);
+        IdentifierCodec<?> obj = identifierCodecs.get(identifier);
         if (obj != null) {
             return obj;
         }
+        return createIdentifierCodec(identifier, identifiable);
+    }
+
+    @Override
+    public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> identifier) {
+        @SuppressWarnings("unchecked")
+        IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(identifier);
+        if (obj != null) {
+            return obj;
+        }
+        Class<? extends Identifiable<T>> identifiable = ClassLoaderUtils.findFirstGenericArgument(identifier,
+                Identifier.class);
+        return createIdentifierCodec(identifier, identifiable);
+    }
+
+    private <T extends Identifier<?>> IdentifierCodec<T> createIdentifierCodec(final Class<T> identifier,
+            final Class<? extends Identifiable<T>> identifiable) {
         Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
-                .keyTransformerForIdentifiable(type);
+                .keyTransformerForIdentifiable(identifiable);
         BindingCodec<Map<QName, Object>, Object> newInstance;
         newInstance = newInstanceOf(newCodec);
-        IdentifierCodecImpl<?> newWrapper = new IdentifierCodecImpl<>(newInstance);
-        identifierCodecs.put(type, newWrapper);
+        IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
+        identifierCodecs.put(identifier, newWrapper);
         return newWrapper;
     }
 
@@ -365,22 +373,6 @@ class LazyGeneratedCodecRegistry implements //
         CodecMapping.setIdentityRefCodec(cls, identityRefCodec);
     }
 
-    @Override
-    public <T extends Identifier<?>> IdentifierCodec<T> getCodecForIdentifier(final Class<T> object) {
-        @SuppressWarnings("unchecked")
-        IdentifierCodec<T> obj = (IdentifierCodec<T>) identifierCodecs.get(object);
-        if (obj != null) {
-            return obj;
-        }
-        Class<? extends BindingCodec<Map<QName, Object>, Object>> newCodec = generator
-                .keyTransformerForIdentifier(object);
-        BindingCodec<Map<QName, Object>, Object> newInstance;
-        newInstance = newInstanceOf(newCodec);
-        IdentifierCodecImpl<T> newWrapper = new IdentifierCodecImpl<>(newInstance);
-        identifierCodecs.put(object, newWrapper);
-        return newWrapper;
-    }
-
     @SuppressWarnings("rawtypes")
     public ChoiceCaseCodecImpl getCaseCodecFor(final Class caseClass) {
         ChoiceCaseCodecImpl<?> potential = caseCodecs.get(caseClass);
@@ -406,8 +398,8 @@ class LazyGeneratedCodecRegistry implements //
         for (Map.Entry<Type, AugmentationSchema> entry : bimap.entrySet()) {
             Type key = entry.getKey();
             AugmentationSchema value = entry.getValue();
-            Set<DataSchemaNode> augmentedNodes = value.getChildNodes();
-            if (augmentedNodes != null && !(augmentedNodes.isEmpty())) {
+            Collection<DataSchemaNode> augmentedNodes = value.getChildNodes();
+            if (augmentedNodes != null && !augmentedNodes.isEmpty()) {
                 typeToAugment.put(key, value);
             }
         }
@@ -433,6 +425,25 @@ class LazyGeneratedCodecRegistry implements //
     @Override
     public void onGlobalContextUpdated(final SchemaContext context) {
         currentSchema = context;
+        resetDispatchCodecsAdaptation();
+
+    }
+
+    /**
+     * Resets / clears adaptation for all schema context sensitive codecs in
+     * order for them to adapt to new schema context and maybe newly discovered
+     * augmentations This ensure correct behaviour for augmentations and
+     * augmented cases for preexisting codecs, which augmentations were
+     * introduced at later point in time.
+     *
+     * This also makes removed augmentations unavailable.
+     */
+    private void resetDispatchCodecsAdaptation() {
+        synchronized (dispatchCodecs) {
+            for (LocationAwareDispatchCodec<?> codec : dispatchCodecs.values()) {
+                codec.resetCodec(this);
+            }
+        }
     }
 
     @SuppressWarnings({ "unchecked", "rawtypes" })
@@ -443,8 +454,11 @@ class LazyGeneratedCodecRegistry implements //
         Preconditions.checkState(oldCodec == null);
         BindingCodec<Map<QName, Object>, Object> delegate = newInstanceOf(choiceCodec);
         PublicChoiceCodecImpl<?> newCodec = new PublicChoiceCodecImpl(delegate);
-        DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass);
+        DispatchChoiceCodecImpl dispatchCodec = new DispatchChoiceCodecImpl(choiceClass, this);
         choiceCodecs.put(choiceClass, newCodec);
+        synchronized (dispatchCodecs) {
+            dispatchCodecs.put(choiceClass, dispatchCodec);
+        }
         CodecMapping.setDispatchCodec(choiceCodec, dispatchCodec);
     }
 
@@ -471,14 +485,17 @@ class LazyGeneratedCodecRegistry implements //
         if (ret != null) {
             return ret;
         }
-        ret = new AugmentableDispatchCodec(dataClass);
+        ret = new AugmentableDispatchCodec(dataClass, this);
         augmentableCodecs.put(dataClass, ret);
+        synchronized (dispatchCodecs) {
+            dispatchCodecs.put(dataClass, ret);
+        }
         ret.tryToLoadImplementations();
         return ret;
     }
 
-    private static abstract class IntermediateCodec<T> implements //
-            DomCodec<T>, Delegator<BindingCodec<Map<QName, Object>, Object>> {
+    private static abstract class IntermediateCodec<T> implements DomCodec<T>,
+            Delegator<BindingCodec<Map<QName, Object>, Object>> {
 
         private final BindingCodec<Map<QName, Object>, Object> delegate;
 
@@ -499,9 +516,8 @@ class LazyGeneratedCodecRegistry implements //
 
     }
 
-    private static class IdentifierCodecImpl<T extends Identifier<?>> //
-            extends IntermediateCodec<T> //
-            implements IdentifierCodec<T> {
+    private static class IdentifierCodecImpl<T extends Identifier<?>> extends IntermediateCodec<T> implements
+            IdentifierCodec<T> {
 
         public IdentifierCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
             super(delegate);
@@ -529,9 +545,8 @@ class LazyGeneratedCodecRegistry implements //
         }
     }
 
-    private static class DataContainerCodecImpl<T extends DataContainer> //
-            extends IntermediateCodec<T> //
-            implements DataContainerCodec<T> {
+    private static class DataContainerCodecImpl<T extends DataContainer> extends IntermediateCodec<T> implements
+            DataContainerCodec<T> {
 
         public DataContainerCodecImpl(final BindingCodec<Map<QName, Object>, Object> delegate) {
             super(delegate);
@@ -567,22 +582,52 @@ class LazyGeneratedCodecRegistry implements //
 
     private interface LocationAwareBindingCodec<P, I> extends BindingCodec<P, I> {
 
-        boolean isApplicable(InstanceIdentifier<?> location);
+        boolean isApplicable(InstanceIdentifier<?> parentPath, CompositeNode data);
 
         public Class<?> getDataType();
 
     }
 
     @SuppressWarnings("rawtypes")
-    private abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements BindingCodec {
+    private static abstract class LocationAwareDispatchCodec<T extends LocationAwareBindingCodec> implements
+            BindingCodec {
 
         private final Map<Class, T> implementations = Collections.synchronizedMap(new WeakHashMap<Class, T>());
         private final Set<InstanceIdentifier<?>> adaptedForPaths = new HashSet<>();
+        private LazyGeneratedCodecRegistry registry;
+
+        protected LocationAwareDispatchCodec(final LazyGeneratedCodecRegistry registry) {
+            this.registry = registry;
+        }
 
         protected Map<Class, T> getImplementations() {
             return implementations;
         }
 
+        /**
+         * Resets codec adaptation based on location and schema context.
+         *
+         * This is required if new cases / augmentations were introduced or
+         * removed and first use of codec is triggered by invocation from DOM to
+         * Java, so the implementations may change and this may require loading
+         * of new codecs and/or removal of existing ones.
+         *
+         */
+        public synchronized void resetCodec(final LazyGeneratedCodecRegistry currentRegistry) {
+            registry = currentRegistry;
+            adaptedForPaths.clear();
+            resetAdaptationImpl();
+        }
+
+        protected void resetAdaptationImpl() {
+            // Intentionally NOOP, subclasses may specify their custom
+            // behaviour.
+        }
+
+        protected final LazyGeneratedCodecRegistry getRegistry() {
+            return registry;
+        }
+
         protected void addImplementation(final T implementation) {
             implementations.put(implementation.getDataType(), implementation);
         }
@@ -592,6 +637,40 @@ class LazyGeneratedCodecRegistry implements //
             throw new UnsupportedOperationException("Invocation of deserialize without Tree location is unsupported");
         }
 
+        @Override
+        public final Object deserialize(final Object parent, final InstanceIdentifier parentPath) {
+            adaptForPath(parentPath);
+            Preconditions.checkArgument(parent instanceof CompositeNode, "node must be of CompositeNode type.");
+            CompositeNode parentData = (CompositeNode) parent;
+            ArrayList<T> applicable = new ArrayList<>(implementations.size());
+
+            /*
+             * Codecs are filtered to only ones, which are applicable in
+             * supplied parent context.
+             */
+            for (T impl : getImplementations().values()) {
+                @SuppressWarnings("unchecked")
+                boolean codecApplicable = impl.isApplicable(parentPath, parentData);
+                if (codecApplicable) {
+                    applicable.add(impl);
+                }
+            }
+            LOG.trace("{}: Deserializing mixins from {}, Schema Location {}, Applicable Codecs: {}, All Codecs: {}",
+                    this, parent, parentPath, applicable, getImplementations().values());
+
+            /*
+             * In case of none is applicable, we return null. Since there is no
+             * mixin which is applicable in this location.
+             */
+            if (applicable.isEmpty()) {
+                return null;
+            }
+            return deserializeImpl(parentData, parentPath, applicable);
+        }
+
+        protected abstract Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> parentPath,
+                Iterable<T> applicableCodecs);
+
         @Override
         public Object serialize(final Object input) {
             Preconditions.checkArgument(input instanceof DataContainer);
@@ -615,14 +694,15 @@ class LazyGeneratedCodecRegistry implements //
             if (adaptedForPaths.contains(path)) {
                 return;
             }
+            LOG.debug("Adapting mixin codec {} for path {}", this, path);
             /**
              * We search in schema context if the use of this location aware
              * codec (augmentable codec, case codec) makes sense on provided
              * location (path)
              *
              */
-            Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(currentSchema,
-                    path);
+            Optional<DataNodeContainer> contextNode = BindingSchemaContextUtils.findDataNodeContainer(
+                    getRegistry().currentSchema, path);
             /**
              * If context node is present, this codec makes sense on provided
              * location.
@@ -646,7 +726,7 @@ class LazyGeneratedCodecRegistry implements //
                          * make sure instance identifier codec is aware of
                          * combination of this path / augmentation / case
                          */
-                        instanceIdentifierCodec.serialize(path);
+                        getRegistry().getInstanceIdentifierCodec().serialize(path);
                     } catch (Exception e) {
                         LOG.warn("Exception during preparation of instance identifier codec for  path {}.", path, e);
                     }
@@ -672,11 +752,6 @@ class LazyGeneratedCodecRegistry implements //
         private final Map<InstanceIdentifier<?>, ChoiceCaseNode> instantiatedLocations;
         private final Class<?> dataType;
 
-        @Override
-        public boolean isApplicable(final InstanceIdentifier location) {
-            return instantiatedLocations.containsKey(location);
-        }
-
         public ChoiceCaseCodecImpl(final Class<?> caseClass, final ChoiceCaseNode caseNode,
                 final BindingCodec newInstance) {
             this.delegate = newInstance;
@@ -751,7 +826,8 @@ class LazyGeneratedCodecRegistry implements //
             }
         }
 
-        public boolean isAcceptable(final InstanceIdentifier path, final CompositeNode input) {
+        @Override
+        public boolean isApplicable(final InstanceIdentifier path, final CompositeNode input) {
             ChoiceCaseNode instantiatedSchema = null;
             synchronized (instantiatedLocations) {
                 instantiatedSchema = instantiatedLocations.get(path);
@@ -762,7 +838,7 @@ class LazyGeneratedCodecRegistry implements //
             return checkAgainstSchema(instantiatedSchema, input);
         }
 
-        protected boolean isAugmenting(final QName choiceName,final QName proposedQName) {
+        protected boolean isAugmenting(final QName choiceName, final QName proposedQName) {
             if (schema.isAugmenting()) {
                 return true;
             }
@@ -772,11 +848,13 @@ class LazyGeneratedCodecRegistry implements //
                 return true;
             }
             if (!parentQName.equals(choiceName)) {
-                // This item is instantiation of choice via uses in other YANG module
-                if(choiceName.getNamespace().equals(schema.getQName())) {
+                // This item is instantiation of choice via uses in other YANG
+                // module
+                if (choiceName.getNamespace().equals(schema.getQName().getNamespace())) {
                     // Original definition of grouping is in same namespace
                     // as original definition of case
-                    // so for sure case is introduced via instantiation of grouping
+                    // so for sure case is introduced via instantiation of
+                    // grouping
                     return false;
                 }
                 // Since we are still here, that means case has same namespace
@@ -787,6 +865,11 @@ class LazyGeneratedCodecRegistry implements //
             }
             return false;
         }
+
+        @Override
+        public String toString() {
+            return "ChoiceCaseCodec [case=" + dataType + ", knownLocations=" + instantiatedLocations.keySet() + "]";
+        }
     }
 
     private static class PublicChoiceCodecImpl<T> implements ChoiceCodec<T>,
@@ -824,27 +907,19 @@ class LazyGeneratedCodecRegistry implements //
         private final Class<?> choiceType;
         private final QName choiceName;
 
-        private DispatchChoiceCodecImpl(final Class<?> type) {
+        private DispatchChoiceCodecImpl(final Class<?> type, final LazyGeneratedCodecRegistry registry) {
+            super(registry);
             choiceType = type;
             choiceName = BindingReflections.findQName(type);
         }
 
         @Override
-        public Object deserialize(final Object input, @SuppressWarnings("rawtypes") final InstanceIdentifier path) {
-            adaptForPath(path);
-
-            if (input instanceof CompositeNode) {
-                List<Entry<Class, ChoiceCaseCodecImpl<?>>> codecs = new ArrayList<>(getImplementations().entrySet());
-                for (Entry<Class, ChoiceCaseCodecImpl<?>> codec : codecs) {
-                    ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
-                    if (caseCodec.isAcceptable(path, (CompositeNode) input)) {
-                        ValueWithQName<?> value = caseCodec.deserialize((CompositeNode) input, path);
-                        if (value != null) {
-                            return value.getValue();
-                        }
-                        return null;
-                    }
-                }
+        public Object deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
+                final Iterable<ChoiceCaseCodecImpl<?>> codecs) {
+            ChoiceCaseCodecImpl<?> caseCodec = Iterables.getOnlyElement(codecs);
+            ValueWithQName<?> value = caseCodec.deserialize(input, path);
+            if (value != null) {
+                return value.getValue();
             }
             return null;
         }
@@ -854,14 +929,14 @@ class LazyGeneratedCodecRegistry implements //
         public Object serialize(final Object input) {
             Preconditions.checkArgument(input instanceof Map.Entry<?, ?>, "Input must be QName, Value");
             @SuppressWarnings("rawtypes")
-            QName derivedQName =  (QName) ((Map.Entry) input).getKey();
-                    @SuppressWarnings("rawtypes")
+            QName derivedQName = (QName) ((Map.Entry) input).getKey();
+            @SuppressWarnings("rawtypes")
             Object inputValue = ((Map.Entry) input).getValue();
             Preconditions.checkArgument(inputValue instanceof DataObject);
             Class<? extends DataContainer> inputType = ((DataObject) inputValue).getImplementedInterface();
             ChoiceCaseCodecImpl<?> codec = tryToLoadImplementation(inputType);
             Preconditions.checkState(codec != null, "Unable to get codec for %s", inputType);
-            if (codec.isAugmenting(choiceName,derivedQName)) {
+            if (codec.isAugmenting(choiceName, derivedQName)) {
                 // If choice is augmenting we use QName which defined this
                 // augmentation
                 return codec.getDelegate().serialize(new ValueWithQName<>(codec.getSchema().getQName(), inputValue));
@@ -869,8 +944,6 @@ class LazyGeneratedCodecRegistry implements //
             return codec.getDelegate().serialize(input);
         }
 
-
-
         @SuppressWarnings("rawtypes")
         protected Optional<ChoiceCaseCodecImpl> tryToLoadImplementation(final Type potential) {
             try {
@@ -911,116 +984,159 @@ class LazyGeneratedCodecRegistry implements //
 
         @Override
         protected void adaptForPathImpl(final InstanceIdentifier<?> augTarget, final DataNodeContainer ctxNode) {
-            Optional<ChoiceNode> newChoice = findInstantiatedChoice(ctxNode, choiceName);
+            Optional<ChoiceNode> newChoice = BindingSchemaContextUtils.findInstantiatedChoice(ctxNode, choiceType);
             tryToLoadImplementations();
             Preconditions.checkState(newChoice.isPresent(), "BUG: Unable to find instantiated choice node in schema.");
             for (@SuppressWarnings("rawtypes")
             Entry<Class, ChoiceCaseCodecImpl<?>> codec : getImplementations().entrySet()) {
                 ChoiceCaseCodecImpl<?> caseCodec = codec.getValue();
-                Optional<ChoiceCaseNode> instantiatedSchema = findInstantiatedCase(newChoice.get(),
-                        caseCodec.getSchema());
+                Optional<ChoiceCaseNode> instantiatedSchema = BindingSchemaContextUtils.findInstantiatedCase(
+                        newChoice.get(), caseCodec.getSchema());
                 if (instantiatedSchema.isPresent()) {
                     caseCodec.adaptForPath(augTarget, instantiatedSchema.get());
                 }
             }
         }
 
-        private Optional<ChoiceNode> findInstantiatedChoice(final DataNodeContainer ctxNode, final QName choiceName) {
-            DataSchemaNode potential = ctxNode.getDataChildByName(choiceName);
-            if (potential == null) {
-                potential = ctxNode.getDataChildByName(choiceName.getLocalName());
-            }
-
-            if (potential instanceof ChoiceNode) {
-                return Optional.of((ChoiceNode) potential);
-            }
-
-            return Optional.absent();
-        }
-
-        private Optional<ChoiceCaseNode> findInstantiatedCase(final ChoiceNode newChoice, final ChoiceCaseNode schema) {
-            ChoiceCaseNode potential = newChoice.getCaseNodeByName(schema.getQName());
-            if (potential != null) {
-                return Optional.of(potential);
-            }
-            // FIXME: Probably requires more extensive check
-            // e.g. we have one choice and two augmentations from different
-            // modules using same local name
-            // but different namespace / contents
-            return Optional.fromNullable(newChoice.getCaseNodeByName(schema.getQName().getLocalName()));
+        @Override
+        public String toString() {
+            return "DispatchChoiceCodecImpl [choiceType=" + choiceType + "]";
         }
     }
 
+    /**
+     *
+     * Dispatch codec for augmented object, which processes augmentations
+     * <p>
+     * This codec is used from DataObject codec generated using
+     * {@link TransformerGenerator#transformerFor(Class)} and is wired during
+     * {@link LazyGeneratedCodecRegistry#onDataContainerCodecCreated(Class, Class)}.
+     * <p>
+     * Instance of this codec is associated with class of Binding DTO which
+     * represents target for augmentations.
+     *
+     */
     @SuppressWarnings({ "rawtypes", "unchecked" })
-    class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
+    static class AugmentableDispatchCodec extends LocationAwareDispatchCodec<AugmentationCodecWrapper> {
 
         private final Class augmentableType;
 
-        public AugmentableDispatchCodec(final Class type) {
+        /**
+         * Construct augmetable dispatch codec.
+         *
+         * @param type
+         *            Class representing augmentation target
+         * @param registry
+         *            Registry with which this codec is associated.
+         */
+        public AugmentableDispatchCodec(final Class type, final LazyGeneratedCodecRegistry registry) {
+            super(registry);
             Preconditions.checkArgument(Augmentable.class.isAssignableFrom(type));
             augmentableType = type;
         }
 
+        /**
+         * Serializes object to list of values which needs to be injected into
+         * resulting DOM Node. Injection of data to parent DOM Node is handled
+         * by caller (in this case generated codec).
+         *
+         * TODO: Deprecate use of augmentation codec without instance instance
+         * identifier
+         *
+         * @return list of nodes, which needs to be added to parent node.
+         *
+         */
         @Override
-        // TODO deprecate use without iid
         public Object serialize(final Object input) {
+            Preconditions.checkArgument(augmentableType.isInstance(input), "Object %s is not instance of %s ", input,
+                    augmentableType);
             if (input instanceof Augmentable<?>) {
-                Map<Class, Augmentation> augmentations = getAugmentations(input);
+                Map<Class<? extends Augmentation<?>>, Augmentation<?>> augmentations = BindingReflections
+                        .getAugmentations((Augmentable<?>) input);
                 return serializeImpl(augmentations);
             }
             return null;
         }
 
-        private Map<Class, Augmentation> getAugmentations(final Object input) {
-            Field augmentationField;
-            try {
-                augmentationField = input.getClass().getDeclaredField("augmentation");
-                augmentationField.setAccessible(true);
-                Map<Class, Augmentation> augMap = (Map<Class, Augmentation>) augmentationField.get(input);
-                return augMap;
-            } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
-                LOG.debug("Could not read augmentations for {}", input, e);
-            }
-            return Collections.emptyMap();
-        }
-
-        @SuppressWarnings("deprecation")
-        private List serializeImpl(final Map<Class, Augmentation> input) {
+        /**
+         *
+         * Serialization of augmentations, returns list of composite nodes,
+         * which needs to be injected to parent node.
+         *
+         * @param input
+         *            Map of classes to augmentations
+         * @return List of nodes, which should be added to parent node.
+         */
+        private List serializeImpl(final Map<Class<? extends Augmentation<?>>, Augmentation<?>> input) {
             List ret = new ArrayList<>();
-            for (Entry<Class, Augmentation> entry : input.entrySet()) {
-                AugmentationCodec codec = getCodecForAugmentation(entry.getKey());
+            for (Entry<Class<? extends Augmentation<?>>, Augmentation<?>> entry : input.entrySet()) {
+                AugmentationCodec codec = getRegistry().getCodecForAugmentation(entry.getKey());
                 CompositeNode node = codec.serialize(new ValueWithQName(null, entry.getValue()));
-                ret.addAll(node.getChildren());
+                ret.addAll(node.getValue());
             }
             return ret;
         }
 
+        /**
+         *
+         * Deserialization of augmentation which is location aware.
+         *
+         * Note: In case of composite nodes as an input, each codec is invoked
+         * since there is no augmentation identifier and we need to look for
+         * concrete classes. FIXME: Maybe faster variation will be by extending
+         * {@link AugmentationCodecWrapper} to look for particular QNames, which
+         * will filter incoming set of codecs.
+         *
+         *
+         * @param input
+         *            Input representation of data
+         * @param path
+         *            Wildcarded instance identifier representing location of
+         *            augmentation parent in conceptual schema tree
+         * @param codecs
+         *            Set of codecs which are applicable for supplied
+         *            <code>path</code>, selected by caller to be used by
+         *            deserialization
+         *
+         *
+         */
         @Override
-        public Map<Class, Augmentation> deserialize(final Object input, final InstanceIdentifier path) {
-            adaptForPath(path);
+        public Map<Class, Augmentation> deserializeImpl(final CompositeNode input, final InstanceIdentifier<?> path,
+                final Iterable<AugmentationCodecWrapper> codecs) {
+            LOG.trace("{}: Going to deserialize augmentations from {} in location {}. Available codecs {}", this,
+                    input, path, codecs);
             Map<Class, Augmentation> ret = new HashMap<>();
-
-            if (input instanceof CompositeNode) {
-                List<Entry<Class, AugmentationCodecWrapper>> codecs = new ArrayList<>(getImplementations().entrySet());
-                for (Entry<Class, AugmentationCodecWrapper> codec : codecs) {
-                    AugmentationCodec<?> ac = codec.getValue();
-                    if (ac.isAcceptable(path)) {
-                        // We add Augmentation Identifier to path, in order to
-                        // correctly identify children.
-                        InstanceIdentifier augmentPath = path.builder().augmentation(codec.getKey()).build();
-                        ValueWithQName<?> value = codec.getValue().deserialize((CompositeNode) input, augmentPath);
-                        if (value != null && value.getValue() != null) {
-                            ret.put(codec.getKey(), (Augmentation) value.getValue());
-                        }
-                    }
+            for (AugmentationCodecWrapper codec : codecs) {
+                // We add Augmentation Identifier to path, in order to
+                // correctly identify children.
+                Class type = codec.getDataType();
+                final InstanceIdentifier augmentPath = path.augmentation(type);
+                ValueWithQName<?> value = codec.deserialize(input, augmentPath);
+                if (value != null && value.getValue() != null) {
+                    ret.put(type, (Augmentation) value.getValue());
                 }
             }
             return ret;
         }
 
+        /**
+         *
+         * Tries to load implementation of concrete augmentation codec for
+         * supplied type
+         *
+         * Loading of codec may fail, because of supplied type may not be
+         * visible by classloaders known by registry. If class was not found
+         * returns {@link Optional#absent()}.
+         *
+         * @param potential
+         *            Augmentation class identifier for which codecs should be
+         *            loaded.
+         * @return Optional with codec for supplied type
+         *
+         */
         protected Optional<AugmentationCodecWrapper> tryToLoadImplementation(final Type potential) {
             try {
-                Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) classLoadingStrategy
+                Class<? extends Augmentation<?>> clazz = (Class<? extends Augmentation<?>>) getRegistry().classLoadingStrategy
                         .loadClass(potential);
                 return Optional.of(tryToLoadImplementation(clazz));
             } catch (ClassNotFoundException e) {
@@ -1031,7 +1147,8 @@ class LazyGeneratedCodecRegistry implements //
 
         @Override
         protected AugmentationCodecWrapper tryToLoadImplementation(final Class inputType) {
-            AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getCodecForAugmentation(inputType);
+            AugmentationCodecWrapper<? extends Augmentation<?>> potentialImpl = getRegistry().getCodecForAugmentation(
+                    inputType);
             addImplementation(potentialImpl);
             return potentialImpl;
         }
@@ -1094,8 +1211,8 @@ class LazyGeneratedCodecRegistry implements //
                         InstanceIdentifier augPath = augTarget.augmentation(augType);
                         try {
 
-                            org.opendaylight.yangtools.yang.data.api.InstanceIdentifier domPath = getInstanceIdentifierCodec()
-                                    .serialize(augPath);
+                            org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier domPath = getRegistry()
+                                    .getInstanceIdentifierCodec().serialize(augPath);
                             if (domPath == null) {
                                 LOG.error("Unable to serialize instance identifier for {}", augPath);
                             }
@@ -1126,6 +1243,12 @@ class LazyGeneratedCodecRegistry implements //
             }
             return null;
         }
+
+        @Override
+        public String toString() {
+            return "AugmentableDispatchCodec [augmentable=" + augmentableType + "]";
+        }
+
     }
 
     @SuppressWarnings("rawtypes")
@@ -1177,9 +1300,6 @@ class LazyGeneratedCodecRegistry implements //
         @Override
         @SuppressWarnings("unchecked")
         public ValueWithQName<T> deserialize(final Node<?> input, final InstanceIdentifier<?> bindingIdentifier) {
-            // if (!isAcceptable(bindingIdentifier)) {
-            // return null;
-            // }
             Object rawCodecValue = getDelegate().deserialize(input, bindingIdentifier);
             return new ValueWithQName<T>(input.getNodeType(), (T) rawCodecValue);
         }
@@ -1198,14 +1318,20 @@ class LazyGeneratedCodecRegistry implements //
         }
 
         @Override
-        public boolean isApplicable(final InstanceIdentifier location) {
-            return isAcceptable(location);
+        public boolean isApplicable(final InstanceIdentifier parentPath, final CompositeNode parentData) {
+            return isAcceptable(parentPath);
         }
 
         @Override
         public Class<?> getDataType() {
             return augmentationType;
         }
+
+        @Override
+        public String toString() {
+            return "AugmentationCodecWrapper [augmentation=" + augmentationType + ", knownLocations="
+                    + validAugmentationTargets.keySet() + "]";
+        }
     }
 
     @SuppressWarnings("rawtypes")
@@ -1219,52 +1345,32 @@ class LazyGeneratedCodecRegistry implements //
 
         @Override
         public Class<?> deserialize(final QName input) {
+            if (input == null) {
+                return null;
+            }
             Type type = qnamesToIdentityMap.get(input);
             if (type == null) {
-                return null;
+                String packageName = BindingMapping.getRootPackageName(input);
+                String className = BindingMapping.getClassName(input);
+                type = new ReferencedTypeImpl(packageName, className);
             }
-            ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
-            WeakReference<Class> softref = typeToClass.get(typeref);
-            if (softref == null) {
-
-                try {
-                    Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
-                    if (cls != null) {
-                        serialize(cls);
-                        return cls;
-                    }
-                } catch (Exception e) {
-                    LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
-                            typeref.getFullyQualifiedName());
+            try {
+                final Class<?> cls = classLoadingStrategy.loadClass(type);
+                if (cls != null) {
+                    serialize(cls);
+                    return cls;
                 }
-                return null;
+            } catch (Exception e) {
+                LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
+                        type.getFullyQualifiedName(), e);
             }
-            return softref.get();
+            return null;
+
         }
 
         @Override
         public Object deserialize(final Object input, final InstanceIdentifier bindingIdentifier) {
-            Type type = qnamesToIdentityMap.get(input);
-            if (type == null) {
-                return null;
-            }
-            ReferencedTypeImpl typeref = new ReferencedTypeImpl(type.getPackageName(), type.getName());
-            WeakReference<Class> softref = typeToClass.get(typeref);
-            if (softref == null) {
-
-                try {
-                    Class<?> cls = classLoadingStrategy.loadClass(typeref.getFullyQualifiedName());
-                    if (cls != null) {
-                        serialize(cls);
-                        return cls;
-                    }
-                } catch (Exception e) {
-                    LOG.warn("Identity {} was not deserialized, because of missing class {}", input,
-                            typeref.getFullyQualifiedName());
-                }
-                return null;
-            }
-            return softref.get();
+            return deserialize(input);
         }
 
         @Override
@@ -1275,8 +1381,7 @@ class LazyGeneratedCodecRegistry implements //
             if (qname != null) {
                 return qname;
             }
-            ConcreteType typeref = Types.typeForClass(input);
-            qname = typeToQname.get(typeref);
+            qname = BindingReflections.findQName(input);
             if (qname != null) {
                 identityQNames.put(input, qname);
             }
@@ -1294,4 +1399,5 @@ class LazyGeneratedCodecRegistry implements //
     private static final Type referencedType(final Class<?> augmentableType) {
         return new ReferencedTypeImpl(augmentableType.getPackage().getName(), augmentableType.getSimpleName());
     }
+
 }