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