Merge branch 'mdsal-trace' from controller
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / ChoiceNodeCodecContext.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.mdsal.binding.dom.codec.impl;
9
10 import com.google.common.base.Preconditions;
11 import com.google.common.collect.ImmutableListMultimap;
12 import com.google.common.collect.ImmutableMap;
13 import com.google.common.collect.ImmutableMap.Builder;
14 import com.google.common.collect.ImmutableSet;
15 import com.google.common.collect.Iterables;
16 import com.google.common.collect.Lists;
17 import com.google.common.collect.MultimapBuilder.SetMultimapBuilder;
18 import com.google.common.collect.Multimaps;
19 import com.google.common.collect.SetMultimap;
20 import java.util.ArrayList;
21 import java.util.Comparator;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.List;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.Set;
29 import java.util.concurrent.ConcurrentHashMap;
30 import javax.annotation.Nonnull;
31 import javax.annotation.Nullable;
32 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
33 import org.opendaylight.yangtools.yang.binding.DataObject;
34 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
40 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
41 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47
48 final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceSchemaNode> {
49     private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
50     private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
51
52     /*
53      * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence
54      * given:
55      *
56      * container foo {
57      *     choice bar {
58      *         leaf baz;
59      *     }
60      * }
61      *
62      * we will see {@code Baz extends ChildOf<Foo>}, which is how the users would address it in InstanceIdentifier
63      * terms. The implicit assumption being made is that {@code Baz} identifies a particular instantiation and hence
64      * provides unambiguous reference to an effective schema statement.
65      *
66      * <p>
67      * Unfortunately this does not quite work with groupings, as their generation has changed: we do not have
68      * interfaces that would capture grouping instantiations, hence we do not have a proper addressing point and
69      * users need to specify the interfaces generated in the grouping's definition. These can be very much
70      * ambiguous, as a {@code grouping} can be used in multiple modules independently within an {@code augment}
71      * targeting {@code choice}, as each instantiation is guaranteed to have a unique namespace -- but we do not
72      * have the appropriate instantiations of those nodes.
73      *
74      * <p>
75      * To address this issue we have a two-class lookup mechanism, which relies on the interface generated for
76      * the {@code case} statement to act as the namespace anchor bridging the nodes inside the grouping to the
77      * namespace in which they are instantiated.
78      *
79      * <p>
80      * Furthermore downstream code relies on historical mechanics, which would guess what the instantiation is,
81      * silently assuming the ambiguity is theoretical and does not occur in practice.
82      *
83      * <p>
84      * This leads to three classes of addressing, in order descending performance requirements.
85      * <ul>
86      *   <li>Direct DataObject, where we name an exact child</li>
87      *   <li>Case DataObject + Grouping DataObject</li>
88      *   <li>Grouping DataObject, which is ambiguous</li>
89      * </ul>
90      *
91      * {@code byCaseChildClass} supports direct DataObject mapping and contains only unambiguous children, while
92      * {@code byClass} supports indirect mapping and contains {@code case} sub-statements.
93      *
94      * ambiguousByCaseChildClass contains ambiguous mappings, for which we end up issuing warnings. We track each
95      * ambiguous reference and issue warnings when they are encountered.
96      */
97     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
98     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
99     private final ImmutableListMultimap<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseChildClass;
100     private final Set<Class<?>> ambiguousByCaseChildWarnings;
101
102     ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
103         super(prototype);
104         final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
105                 new HashMap<>();
106         final Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
107         final SetMultimap<Class<?>, DataContainerCodecPrototype<?>> childToCase = SetMultimapBuilder.hashKeys()
108                 .hashSetValues().build();
109         final Set<Class<?>> potentialSubstitutions = new HashSet<>();
110         // Walks all cases for supplied choice in current runtime context
111         for (final Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
112             // We try to load case using exact match thus name
113             // and original schema must equals
114             final DataContainerCodecPrototype<CaseSchemaNode> cazeDef = loadCase(caze);
115             // If we have case definition, this case is instantiated
116             // at current location and thus is valid in context of parent choice
117             if (cazeDef != null) {
118                 byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
119                 // Updates collection of case children
120                 @SuppressWarnings("unchecked")
121                 final Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
122                 for (final Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
123                     childToCase.put(cazeChild, cazeDef);
124                 }
125                 // Updates collection of YANG instance identifier to case
126                 for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) {
127                     if (cazeChild.isAugmenting()) {
128                         final AugmentationSchemaNode augment = SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(),
129                             cazeChild);
130                         if (augment != null) {
131                             byYangCaseChildBuilder.put(SchemaUtils.getNodeIdentifierForAugmentation(augment), cazeDef);
132                             continue;
133                         }
134                     }
135                     byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
136                 }
137             } else {
138                 /*
139                  * If case definition is not available, we store it for
140                  * later check if it could be used as substitution of existing one.
141                  */
142                 potentialSubstitutions.add(caze);
143             }
144         }
145         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
146
147         // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
148         final ImmutableListMultimap.Builder<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseBuilder =
149                 ImmutableListMultimap.builder();
150         final Builder<Class<?>, DataContainerCodecPrototype<?>> unambiguousByCaseBuilder = ImmutableMap.builder();
151         for (Entry<Class<?>, Set<DataContainerCodecPrototype<?>>> e : Multimaps.asMap(childToCase).entrySet()) {
152             final Set<DataContainerCodecPrototype<?>> cases = e.getValue();
153             if (cases.size() != 1) {
154                 // Sort all possibilities by their FQCN to retain semi-predictable results
155                 final List<DataContainerCodecPrototype<?>> list = new ArrayList<>(e.getValue());
156                 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
157                 ambiguousByCaseBuilder.putAll(e.getKey(), list);
158             } else {
159                 unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
160             }
161         }
162         byCaseChildClass = unambiguousByCaseBuilder.build();
163
164         // Setup ambiguous tracking, if needed
165         ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
166         ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
167                 : ConcurrentHashMap.newKeySet();
168
169         final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
170         /*
171          * Walks all cases which are not directly instantiated and
172          * tries to match them to instantiated cases - represent same data as instantiated case,
173          * only case name or schema path is different. This is required due property of
174          * binding specification, that if choice is in grouping schema path location is lost,
175          * and users may use incorrect case class using copy builders.
176          */
177         for (final Class<?> substitution : potentialSubstitutions) {
178             search: for (final Entry<Class<?>, DataContainerCodecPrototype<?>> real : byClassBuilder.entrySet()) {
179                 if (BindingReflections.isSubstitutionFor(substitution, real.getKey())) {
180                     bySubstitutionBuilder.put(substitution, real.getValue());
181                     break search;
182                 }
183             }
184         }
185         byClassBuilder.putAll(bySubstitutionBuilder);
186         byClass = ImmutableMap.copyOf(byClassBuilder);
187     }
188
189     @SuppressWarnings("unchecked")
190     @Override
191     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
192         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
193         return (DataContainerCodecContext<C, ?>) childNonNull(child, childClass,
194             "Supplied class %s is not valid case in %s", childClass, bindingArg()).get();
195     }
196
197     @SuppressWarnings("unchecked")
198     @Override
199     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
200             final Class<C> childClass) {
201         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
202         if (child != null) {
203             return Optional.of((DataContainerCodecContext<C, ?>) child.get());
204         }
205         return Optional.empty();
206     }
207
208     Iterable<Class<?>> getCaseChildrenClasses() {
209         return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
210     }
211
212     protected DataContainerCodecPrototype<CaseSchemaNode> loadCase(final Class<?> childClass) {
213         final Optional<CaseSchemaNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(),
214             childClass);
215         if (childSchema.isPresent()) {
216             return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
217         }
218
219         LOG.debug("Supplied class %s is not valid case in schema %s", childClass, getSchema());
220         return null;
221     }
222
223     @Override
224     public NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
225         final DataContainerCodecPrototype<?> cazeProto;
226         if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
227             cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
228         } else {
229             cazeProto = byYangCaseChild.get(arg);
230         }
231
232         return childNonNull(cazeProto, arg,"Argument %s is not valid child of %s", arg, getSchema()).get()
233                 .yangPathArgumentChild(arg);
234     }
235
236     @SuppressWarnings("unchecked")
237     @Override
238     @Nullable
239     public D deserialize(final NormalizedNode<?, ?> data) {
240         Preconditions.checkArgument(data instanceof ChoiceNode);
241         final NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>> casted =
242                 (NormalizedNodeContainer<?, ?, NormalizedNode<?, ?>>) data;
243         final NormalizedNode<?, ?> first = Iterables.getFirst(casted.getValue(), null);
244
245         if (first == null) {
246             return null;
247         }
248         final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
249         return (D) caze.get().deserialize(data);
250     }
251
252     @Override
253     protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
254         return deserialize(normalizedNode);
255     }
256
257     @Override
258     public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
259         Preconditions.checkArgument(getDomPathArgument().equals(arg));
260         return null;
261     }
262
263     @Override
264     public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
265         // FIXME: check for null, since binding container is null.
266         return getDomPathArgument();
267     }
268
269     DataContainerCodecContext<?, ?> getCaseByChildClass(final @Nonnull Class<? extends DataObject> type) {
270         DataContainerCodecPrototype<?> result = byCaseChildClass.get(type);
271         if (result == null) {
272             // We have not found an unambiguous result, try ambiguous ones
273             final List<DataContainerCodecPrototype<?>> inexact = ambiguousByCaseChildClass.get(type);
274             if (!inexact.isEmpty()) {
275                 result = inexact.get(0);
276                 // Issue a warning, but only once so as not to flood the logs
277                 if (ambiguousByCaseChildWarnings.add(type)) {
278                     LOG.warn("Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping "
279                             + "is not guaranteed to be stable and is subject to variations based on runtime "
280                             + "circumstances. Please see the stack trace for hints about the source of ambiguity.",
281                             type, bindingArg(), result.getBindingClass(),
282                             Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
283                 }
284             }
285         }
286
287         return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();
288     }
289 }