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