2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
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;
27 import java.util.Map.Entry;
28 import java.util.Optional;
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;
53 * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence given:
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.
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.
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.
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.
85 * This leads to three classes of addressing, in order descending performance requirements.
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>
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.
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}.
99 final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceRuntimeType> {
100 private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
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;
108 ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceRuntimeType> prototype) {
110 final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
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);
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(
139 (DataSchemaNode) cazeDef.getType().statement(), cazeChild);
140 if (augment != null) {
141 byYangCaseChildBuilder.put(DataSchemaContextNode.augmentationIdentifierFrom(augment),
146 byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
151 * If case definition is not available, we store it for
152 * later check if it could be used as substitution of existing one.
154 potentialSubstitutions.add(caze);
157 byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
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);
171 unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
174 byCaseChildClass = unambiguousByCaseBuilder.build();
176 // Setup ambiguous tracking, if needed
177 ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
178 ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
179 : ConcurrentHashMap.newKeySet();
181 final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
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.
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());
197 byClassBuilder.putAll(bySubstitutionBuilder);
198 byClass = ImmutableMap.copyOf(byClassBuilder);
201 private List<Class<?>> loadCaseClasses() {
202 final var context = factory().getRuntimeContext();
203 final var type = getType();
205 return Stream.concat(type.validCaseChildren().stream(), type.additionalCaseChildren().stream())
207 final var caseName = caseChild.getIdentifier();
209 return context.loadClass(caseName);
210 } catch (ClassNotFoundException e) {
211 throw new IllegalStateException("Failed to load class for " + caseName, e);
214 .collect(Collectors.toUnmodifiableList());
218 public WithStatus getSchema() {
219 // FIXME: Bad cast, we should be returning an EffectiveStatement perhaps?
220 return (WithStatus) getType().statement();
223 @SuppressWarnings("unchecked")
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();
231 @SuppressWarnings("unchecked")
233 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
234 final Class<C> childClass) {
235 final DataContainerCodecPrototype<?> child = byClass.get(childClass);
237 return Optional.of((DataContainerCodecContext<C, ?>) child.get());
239 return Optional.empty();
242 Iterable<Class<?>> getCaseChildrenClasses() {
243 return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
246 protected DataContainerCodecPrototype<CaseRuntimeType> loadCase(final Class<?> childClass) {
247 final var child = getType().bindingCaseChild(JavaTypeName.create(childClass));
249 LOG.debug("Supplied class {} is not valid case in schema {}", childClass, getSchema());
253 return DataContainerCodecPrototype.from(childClass, child, factory());
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()));
262 cazeProto = byYangCaseChild.get(arg);
265 return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
266 .yangPathArgumentChild(arg);
269 @SuppressWarnings("unchecked")
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);
277 // FIXME: this needs to be sorted out
280 final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
281 return (D) caze.get().deserialize(data);
285 protected Object deserializeObject(final NormalizedNode normalizedNode) {
286 return deserialize(normalizedNode);
290 public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
291 checkArgument(getDomPathArgument().equals(arg));
296 public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
297 // FIXME: check for null, since binding container is null.
298 return getDomPathArgument();
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());
319 return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();