Unify getStreamChild() implementations
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / ChoiceCodecContext.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.ImmutableCollection;
13 import com.google.common.collect.ImmutableListMultimap;
14 import com.google.common.collect.ImmutableMap;
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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
21 import java.util.ArrayList;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.LinkedList;
26 import java.util.Set;
27 import java.util.concurrent.ConcurrentHashMap;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
31 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
32 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
33 import org.opendaylight.mdsal.binding.runtime.api.CaseRuntimeType;
34 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
35 import org.opendaylight.yangtools.yang.binding.BindingObject;
36 import org.opendaylight.yangtools.yang.binding.DataContainer;
37 import org.opendaylight.yangtools.yang.binding.DataObject;
38 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
40 import org.opendaylight.yangtools.yang.binding.contract.Naming;
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.YangInstanceIdentifier.NodeIdentifierWithPredicates;
44 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
45 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50
51 /**
52  * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence given:
53  *
54  * <pre>
55  *   <code>
56  *     container foo {
57  *       choice bar {
58  *         leaf baz;
59  *       }
60  *     }
61  *   </code>
62  * </pre>
63  * we will see {@code Baz extends ChildOf<Foo>}, which is how the users would address it in InstanceIdentifier terms.
64  * The implicit assumption being made is that {@code Baz} identifies a particular instantiation and hence provides
65  * unambiguous reference to an effective schema statement.
66  *
67  * <p>
68  * Unfortunately this does not quite work with groupings, as their generation has changed: we do not have interfaces
69  * that would capture grouping instantiations, hence we do not have a proper addressing point and users need to specify
70  * the interfaces generated in the grouping's definition. These can be very much ambiguous, as a {@code grouping} can be
71  * used in multiple modules independently within an {@code augment} targeting {@code choice}, as each instantiation is
72  * guaranteed to have a unique namespace -- but we do not 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 the
76  * {@code case} statement to act as the namespace anchor bridging the nodes inside the grouping to the namespace in
77  * which they are instantiated.
78  *
79  * <p>
80  * Furthermore downstream code relies on historical mechanics, which would guess what the instantiation is, silently
81  * 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  * {@link #byCaseChildClass} supports direct DataObject mapping and contains only unambiguous children, while
92  * {@link #byClass} supports indirect mapping and contains {@code case} sub-statements.
93  *
94  * {@link #ambiguousByCaseChildClass} contains ambiguous mappings, for which we end up issuing warnings. We track each
95  * ambiguous reference and issue warn once when they are encountered -- tracking warning information in
96  * {@link #ambiguousByCaseChildWarnings}.
97  */
98 final class ChoiceCodecContext<D extends DataObject> extends CommonDataObjectCodecContext<D, ChoiceRuntimeType>
99         implements BindingDataObjectCodecTreeNode<D> {
100     private static final Logger LOG = LoggerFactory.getLogger(ChoiceCodecContext.class);
101
102     private final ImmutableListMultimap<Class<?>, CommonDataObjectCodecPrototype<?>> ambiguousByCaseChildClass;
103     private final ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> byCaseChildClass;
104     private final ImmutableMap<NodeIdentifier, CaseCodecPrototype> byYangCaseChild;
105     private final ImmutableMap<Class<?>, CommonDataObjectCodecPrototype<?>> byClass;
106     private final Set<Class<?>> ambiguousByCaseChildWarnings;
107
108     ChoiceCodecContext(final Class<D> cls, final ChoiceRuntimeType type, final CodecContextFactory factory) {
109         this(new ChoiceCodecPrototype(Item.of(cls), type, factory));
110     }
111
112     ChoiceCodecContext(final ChoiceCodecPrototype prototype) {
113         super(prototype);
114         final var byYangCaseChildBuilder = new HashMap<NodeIdentifier, CaseCodecPrototype>();
115         final var byClassBuilder = new HashMap<Class<?>, CommonDataObjectCodecPrototype<?>>();
116         final var childToCase = SetMultimapBuilder.hashKeys().hashSetValues()
117             .<Class<?>, CommonDataObjectCodecPrototype<?>>build();
118
119         // Load case statements valid in this choice and keep track of their names
120         final var choiceType = prototype.getType();
121         final var factory = prototype.getFactory();
122         final var localCases = new HashSet<JavaTypeName>();
123         for (var caseType : choiceType.validCaseChildren()) {
124             @SuppressWarnings("unchecked")
125             final var caseClass = (Class<? extends DataObject>) loadCase(factory.getRuntimeContext(), caseType);
126             final var caseProto = new CaseCodecPrototype(caseClass, caseType, factory);
127
128             localCases.add(caseType.getIdentifier());
129             byClassBuilder.put(caseClass, caseProto);
130
131             // Updates collection of case children
132             for (var cazeChild : getChildrenClasses(caseClass)) {
133                 childToCase.put(cazeChild, caseProto);
134             }
135             // Updates collection of YANG instance identifier to case
136             for (var stmt : caseType.statement().effectiveSubstatements()) {
137                 if (stmt instanceof DataSchemaNode cazeChild) {
138                     byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), caseProto);
139                 }
140             }
141         }
142         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
143
144         // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
145         final var ambiguousByCaseBuilder = ImmutableListMultimap.<Class<?>, CommonDataObjectCodecPrototype<?>>builder();
146         final var unambiguousByCaseBuilder = ImmutableMap.<Class<?>, CommonDataObjectCodecPrototype<?>>builder();
147         for (var entry : Multimaps.asMap(childToCase).entrySet()) {
148             final var cases = entry.getValue();
149             if (cases.size() != 1) {
150                 // Sort all possibilities by their FQCN to retain semi-predictable results
151                 final var list = new ArrayList<>(entry.getValue());
152                 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
153                 ambiguousByCaseBuilder.putAll(entry.getKey(), list);
154             } else {
155                 unambiguousByCaseBuilder.put(entry.getKey(), cases.iterator().next());
156             }
157         }
158         byCaseChildClass = unambiguousByCaseBuilder.build();
159
160         // Setup ambiguous tracking, if needed
161         ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
162         ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
163                 : ConcurrentHashMap.newKeySet();
164
165         /*
166          * Choice/Case mapping across groupings is compile-time unsafe and we therefore need to also track any
167          * CaseRuntimeTypes added to the choice in other contexts. This is necessary to discover when a case represents
168          * equivalent data in a different instantiation context.
169          *
170          * This is required due property of binding specification, that if choice is in grouping schema path location is
171          * lost, and users may use incorrect case class using copy builders.
172          */
173         final var bySubstitutionBuilder = new HashMap<Class<?>, CommonDataObjectCodecPrototype<?>>();
174         final var context = factory.getRuntimeContext();
175         for (var caseType : context.getTypes().allCaseChildren(choiceType)) {
176             final var caseName = caseType.getIdentifier();
177             if (!localCases.contains(caseName)) {
178                 // FIXME: do not rely on class loading here, the check we are performing should be possible on
179                 //        GeneratedType only -- or it can be provided by BindingRuntimeTypes -- i.e. rather than
180                 //        'allCaseChildren()' it would calculate additional mappings we can use off-the-bat.
181                 final var substitution = loadCase(context, caseType);
182
183                 search: for (var real : byClassBuilder.entrySet()) {
184                     if (isSubstitutionFor(substitution, real.getKey())) {
185                         bySubstitutionBuilder.put(substitution, real.getValue());
186                         break search;
187                     }
188                 }
189             }
190         }
191
192         byClassBuilder.putAll(bySubstitutionBuilder);
193         byClass = ImmutableMap.copyOf(byClassBuilder);
194     }
195
196     private static Class<?> loadCase(final BindingRuntimeContext context, final CaseRuntimeType caseType) {
197         final var className = caseType.getIdentifier();
198         try {
199             return context.loadClass(className);
200         } catch (ClassNotFoundException e) {
201             throw new LinkageError("Failed to load class for " + className, e);
202         }
203     }
204
205     @Override
206     public WithStatus getSchema() {
207         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
208         return (WithStatus) type().statement();
209     }
210
211     @SuppressWarnings("unchecked")
212     @Override
213     public <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(final Class<C> childClass) {
214         final var child = byClass.get(childClass);
215         return child == null ? null : (CommonDataObjectCodecContext<C, ?>) child.get();
216     }
217
218     Iterable<Class<?>> getCaseChildrenClasses() {
219         return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
220     }
221
222     @Override
223     public CodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
224         final CommonDataObjectCodecPrototype<?> cazeProto;
225         if (arg instanceof NodeIdentifierWithPredicates) {
226             cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
227         } else {
228             cazeProto = byYangCaseChild.get(arg);
229         }
230
231         return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
232                 .yangPathArgumentChild(arg);
233     }
234
235     @Override
236     @SuppressWarnings("unchecked")
237     @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "See FIXME below")
238     public D deserialize(final NormalizedNode data) {
239         final var casted = checkDataArgument(ChoiceNode.class, data);
240         final var first = Iterables.getFirst(casted.body(), null);
241
242         if (first == null) {
243             // FIXME: this needs to be sorted out
244             return null;
245         }
246         final var caze = byYangCaseChild.get(first.name());
247         return ((CaseCodecContext<D>) caze.get()).deserialize(data);
248     }
249
250     @Override
251     public NormalizedNode serialize(final D data) {
252         return serializeImpl(data);
253     }
254
255     @Override
256     protected Object deserializeObject(final NormalizedNode normalizedNode) {
257         return deserialize(normalizedNode);
258     }
259
260     @Override
261     public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
262         checkArgument(getDomPathArgument().equals(arg));
263         return null;
264     }
265
266     @Override
267     public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
268         // FIXME: check for null, since binding container is null.
269         return getDomPathArgument();
270     }
271
272     @Override
273     public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
274             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
275         return createCachingCodec(this, cacheSpecifier);
276     }
277
278     DataContainerCodecContext<?, ?> getCaseByChildClass(final @NonNull Class<? extends DataObject> type) {
279         var result = byCaseChildClass.get(type);
280         if (result == null) {
281             // We have not found an unambiguous result, try ambiguous ones
282             final var inexact = ambiguousByCaseChildClass.get(type);
283             if (!inexact.isEmpty()) {
284                 result = inexact.get(0);
285                 // Issue a warning, but only once so as not to flood the logs
286                 if (ambiguousByCaseChildWarnings.add(type)) {
287                     LOG.warn("""
288                         Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping is \
289                         not guaranteed to be stable and is subject to variations based on runtime circumstances. \
290                         Please see the stack trace for hints about the source of ambiguity.""",
291                         type, bindingArg(), result.getBindingClass(),
292                         Lists.transform(inexact, CommonDataObjectCodecPrototype::getBindingClass), new Throwable());
293                 }
294             }
295         }
296
297         return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();
298     }
299
300     /**
301      * Scans supplied class and returns an iterable of all data children classes.
302      *
303      * @param type
304      *            YANG Modeled Entity derived from DataContainer
305      * @return Iterable of all data children, which have YANG modeled entity
306      */
307     // FIXME: MDSAL-780: replace use of this method
308     @SuppressWarnings("unchecked")
309     private static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
310         checkArgument(type != null, "Target type must not be null");
311         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
312         final var ret = new LinkedList<Class<? extends DataObject>>();
313         for (var method : type.getMethods()) {
314             AbstractDataContainerAnalysis.getYangModeledReturnType(method, Naming.GETTER_PREFIX)
315                 .ifPresent(entity -> ret.add((Class<? extends DataObject>) entity));
316         }
317         return ret;
318     }
319 }