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