Split out CaseNodeCodecContext.Prototype
[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.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.Optional;
27 import java.util.Set;
28 import java.util.concurrent.ConcurrentHashMap;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
32 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
33 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
34 import org.opendaylight.mdsal.binding.runtime.api.CaseRuntimeType;
35 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
36 import org.opendaylight.yangtools.yang.binding.BindingObject;
37 import org.opendaylight.yangtools.yang.binding.DataContainer;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
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 ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceRuntimeType>
99         implements BindingDataObjectCodecTreeNode<D> {
100     private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
101
102     private final ImmutableMap<NodeIdentifier, DataContainerCodecPrototype<?>> byYangCaseChild;
103     private final ImmutableListMultimap<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseChildClass;
104     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
105     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
106     private final Set<Class<?>> ambiguousByCaseChildWarnings;
107
108     ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceRuntimeType> prototype) {
109         super(prototype);
110         final var byYangCaseChildBuilder = new HashMap<NodeIdentifier, DataContainerCodecPrototype<?>>();
111         final var byClassBuilder = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
112         final var childToCase = SetMultimapBuilder.hashKeys().hashSetValues()
113             .<Class<?>, DataContainerCodecPrototype<?>>build();
114
115         // Load case statements valid in this choice and keep track of their names
116         final var choiceType = prototype.getType();
117         final var factory = prototype.getFactory();
118         final var localCases = new HashSet<JavaTypeName>();
119         for (var caseType : choiceType.validCaseChildren()) {
120             final var caseProto = new CaseNodeCodecContext.Prototype(loadCase(factory.getRuntimeContext(), caseType),
121                 caseType, factory);
122
123             localCases.add(caseType.getIdentifier());
124             byClassBuilder.put(caseProto.getBindingClass(), caseProto);
125
126             // Updates collection of case children
127             @SuppressWarnings("unchecked")
128             final var cazeCls = (Class<? extends DataObject>) caseProto.getBindingClass();
129             for (var cazeChild : getChildrenClasses(cazeCls)) {
130                 childToCase.put(cazeChild, caseProto);
131             }
132             // Updates collection of YANG instance identifier to case
133             for (var stmt : caseProto.getType().statement().effectiveSubstatements()) {
134                 if (stmt instanceof DataSchemaNode cazeChild) {
135                     byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), caseProto);
136                 }
137             }
138         }
139         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
140
141         // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
142         final var ambiguousByCaseBuilder = ImmutableListMultimap.<Class<?>, DataContainerCodecPrototype<?>>builder();
143         final var unambiguousByCaseBuilder = ImmutableMap.<Class<?>, DataContainerCodecPrototype<?>>builder();
144         for (var entry : Multimaps.asMap(childToCase).entrySet()) {
145             final var cases = entry.getValue();
146             if (cases.size() != 1) {
147                 // Sort all possibilities by their FQCN to retain semi-predictable results
148                 final var list = new ArrayList<>(entry.getValue());
149                 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
150                 ambiguousByCaseBuilder.putAll(entry.getKey(), list);
151             } else {
152                 unambiguousByCaseBuilder.put(entry.getKey(), cases.iterator().next());
153             }
154         }
155         byCaseChildClass = unambiguousByCaseBuilder.build();
156
157         // Setup ambiguous tracking, if needed
158         ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
159         ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
160                 : ConcurrentHashMap.newKeySet();
161
162         /*
163          * Choice/Case mapping across groupings is compile-time unsafe and we therefore need to also track any
164          * CaseRuntimeTypes added to the choice in other contexts. This is necessary to discover when a case represents
165          * equivalent data in a different instantiation context.
166          *
167          * This is required due property of binding specification, that if choice is in grouping schema path location is
168          * lost, and users may use incorrect case class using copy builders.
169          */
170         final var bySubstitutionBuilder = new HashMap<Class<?>, DataContainerCodecPrototype<?>>();
171         final var context = factory.getRuntimeContext();
172         for (var caseType : context.getTypes().allCaseChildren(choiceType)) {
173             final var caseName = caseType.getIdentifier();
174             if (!localCases.contains(caseName)) {
175                 // FIXME: do not rely on class loading here, the check we are performing should be possible on
176                 //        GeneratedType only -- or it can be provided by BindingRuntimeTypes -- i.e. rather than
177                 //        'allCaseChildren()' it would calculate additional mappings we can use off-the-bat.
178                 final var substitution = loadCase(context, caseType);
179
180                 search: for (var real : byClassBuilder.entrySet()) {
181                     if (isSubstitutionFor(substitution, real.getKey())) {
182                         bySubstitutionBuilder.put(substitution, real.getValue());
183                         break search;
184                     }
185                 }
186             }
187         }
188
189         byClassBuilder.putAll(bySubstitutionBuilder);
190         byClass = ImmutableMap.copyOf(byClassBuilder);
191     }
192
193     private static Class<?> loadCase(final BindingRuntimeContext context, final CaseRuntimeType caseType) {
194         final var className = caseType.getIdentifier();
195         try {
196             return context.loadClass(className);
197         } catch (ClassNotFoundException e) {
198             throw new LinkageError("Failed to load class for " + className, e);
199         }
200     }
201
202     @Override
203     public WithStatus getSchema() {
204         // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
205         return (WithStatus) getType().statement();
206     }
207
208     @SuppressWarnings("unchecked")
209     @Override
210     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
211         final var child = byClass.get(childClass);
212         return (DataContainerCodecContext<C, ?>) childNonNull(child, childClass,
213             "Supplied class %s is not valid case in %s", childClass, bindingArg()).get();
214     }
215
216     @SuppressWarnings("unchecked")
217     @Override
218     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
219             final Class<C> childClass) {
220         final var child = byClass.get(childClass);
221         if (child != null) {
222             return Optional.of((DataContainerCodecContext<C, ?>) child.get());
223         }
224         return Optional.empty();
225     }
226
227     Iterable<Class<?>> getCaseChildrenClasses() {
228         return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
229     }
230
231     @Override
232     public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
233         final DataContainerCodecPrototype<?> cazeProto;
234         if (arg instanceof NodeIdentifierWithPredicates) {
235             cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
236         } else {
237             cazeProto = byYangCaseChild.get(arg);
238         }
239
240         return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
241                 .yangPathArgumentChild(arg);
242     }
243
244     @Override
245     @SuppressWarnings("unchecked")
246     @SuppressFBWarnings(value = "NP_NONNULL_RETURN_VIOLATION", justification = "See FIXME below")
247     public D deserialize(final NormalizedNode data) {
248         final var casted = checkDataArgument(ChoiceNode.class, data);
249         final var first = Iterables.getFirst(casted.body(), null);
250
251         if (first == null) {
252             // FIXME: this needs to be sorted out
253             return null;
254         }
255         final var caze = byYangCaseChild.get(first.name());
256         return (D) caze.getDataObject().deserialize(data);
257     }
258
259     @Override
260     public NormalizedNode serialize(final D data) {
261         return serializeImpl(data);
262     }
263
264     @Override
265     protected Object deserializeObject(final NormalizedNode normalizedNode) {
266         return deserialize(normalizedNode);
267     }
268
269     @Override
270     public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
271         checkArgument(getDomPathArgument().equals(arg));
272         return null;
273     }
274
275     @Override
276     public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
277         // FIXME: check for null, since binding container is null.
278         return getDomPathArgument();
279     }
280
281     @Override
282     public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
283             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
284         return createCachingCodec(this, cacheSpecifier);
285     }
286
287     DataContainerCodecContext<?, ?> getCaseByChildClass(final @NonNull Class<? extends DataObject> type) {
288         var result = byCaseChildClass.get(type);
289         if (result == null) {
290             // We have not found an unambiguous result, try ambiguous ones
291             final var inexact = ambiguousByCaseChildClass.get(type);
292             if (!inexact.isEmpty()) {
293                 result = inexact.get(0);
294                 // Issue a warning, but only once so as not to flood the logs
295                 if (ambiguousByCaseChildWarnings.add(type)) {
296                     LOG.warn("""
297                         Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping is \
298                         not guaranteed to be stable and is subject to variations based on runtime circumstances. \
299                         Please see the stack trace for hints about the source of ambiguity.""",
300                         type, bindingArg(), result.getBindingClass(),
301                         Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
302                 }
303             }
304         }
305
306         return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();
307     }
308
309     /**
310      * Scans supplied class and returns an iterable of all data children classes.
311      *
312      * @param type
313      *            YANG Modeled Entity derived from DataContainer
314      * @return Iterable of all data children, which have YANG modeled entity
315      */
316     // FIXME: MDSAL-780: replace use of this method
317     @SuppressWarnings("unchecked")
318     private static Iterable<Class<? extends DataObject>> getChildrenClasses(final Class<? extends DataContainer> type) {
319         checkArgument(type != null, "Target type must not be null");
320         checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type must be derived from DataContainer");
321         final var ret = new LinkedList<Class<? extends DataObject>>();
322         for (var method : type.getMethods()) {
323             final var entity = getYangModeledReturnType(method, Naming.GETTER_PREFIX);
324             if (entity.isPresent()) {
325                 ret.add((Class<? extends DataObject>) entity.orElseThrow());
326             }
327         }
328         return ret;
329     }
330 }