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