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