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 org.eclipse.jdt.annotation.NonNull;
32 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
33 import org.opendaylight.yangtools.yang.binding.DataObject;
34 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
37 import org.opendaylight.yangtools.yang.data.api.schema.ChoiceNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.schema.SchemaUtils;
40 import org.opendaylight.yangtools.yang.data.util.DataSchemaContextNode;
41 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
49 * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence given:
60 * we will see {@code Baz extends ChildOf<Foo>}, which is how the users would address it in InstanceIdentifier terms.
61 * The implicit assumption being made is that {@code Baz} identifies a particular instantiation and hence provides
62 * unambiguous reference to an effective schema statement.
65 * Unfortunately this does not quite work with groupings, as their generation has changed: we do not have interfaces
66 * that would capture grouping instantiations, hence we do not have a proper addressing point and users need to specify
67 * the interfaces generated in the grouping's definition. These can be very much ambiguous, as a {@code grouping} can be
68 * used in multiple modules independently within an {@code augment} targeting {@code choice}, as each instantiation is
69 * guaranteed to have a unique namespace -- but we do not have the appropriate instantiations of those nodes.
72 * To address this issue we have a two-class lookup mechanism, which relies on the interface generated for the
73 * {@code case} statement to act as the namespace anchor bridging the nodes inside the grouping to the namespace in
74 * which they are instantiated.
77 * Furthermore downstream code relies on historical mechanics, which would guess what the instantiation is, silently
78 * assuming the ambiguity is theoretical and does not occur in practice.
81 * This leads to three classes of addressing, in order descending performance requirements.
83 * <li>Direct DataObject, where we name an exact child</li>
84 * <li>Case DataObject + Grouping DataObject</li>
85 * <li>Grouping DataObject, which is ambiguous</li>
88 * {@link #byCaseChildClass} supports direct DataObject mapping and contains only unambiguous children, while
89 * {@link #byClass} supports indirect mapping and contains {@code case} sub-statements.
91 * {@link #ambiguousByCaseChildClass} contains ambiguous mappings, for which we end up issuing warnings. We track each
92 * ambiguous reference and issue warn once when they are encountered -- tracking warning information in
93 * {@link #ambiguousByCaseChildWarnings}.
95 final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceSchemaNode> {
96 private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
98 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
99 private final ImmutableListMultimap<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseChildClass;
100 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
101 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
102 private final Set<Class<?>> ambiguousByCaseChildWarnings;
104 ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
106 final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
108 final Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
109 final SetMultimap<Class<?>, DataContainerCodecPrototype<?>> childToCase =
110 SetMultimapBuilder.hashKeys().hashSetValues().build();
111 final Set<Class<?>> potentialSubstitutions = new HashSet<>();
112 // Walks all cases for supplied choice in current runtime context
113 for (final Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
114 // We try to load case using exact match thus name
115 // and original schema must equals
116 final DataContainerCodecPrototype<CaseSchemaNode> cazeDef = loadCase(caze);
117 // If we have case definition, this case is instantiated
118 // at current location and thus is valid in context of parent choice
119 if (cazeDef != null) {
120 byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
121 // Updates collection of case children
122 @SuppressWarnings("unchecked")
123 final Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
124 for (final Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
125 childToCase.put(cazeChild, cazeDef);
127 // Updates collection of YANG instance identifier to case
128 for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) {
129 if (cazeChild.isAugmenting()) {
130 final AugmentationSchemaNode augment = SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(),
132 if (augment != null) {
133 byYangCaseChildBuilder.put(DataSchemaContextNode.augmentationIdentifierFrom(augment),
138 byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
142 * If case definition is not available, we store it for
143 * later check if it could be used as substitution of existing one.
145 potentialSubstitutions.add(caze);
148 byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
150 // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
151 final ImmutableListMultimap.Builder<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseBuilder =
152 ImmutableListMultimap.builder();
153 final Builder<Class<?>, DataContainerCodecPrototype<?>> unambiguousByCaseBuilder = ImmutableMap.builder();
154 for (Entry<Class<?>, Set<DataContainerCodecPrototype<?>>> e : Multimaps.asMap(childToCase).entrySet()) {
155 final Set<DataContainerCodecPrototype<?>> cases = e.getValue();
156 if (cases.size() != 1) {
157 // Sort all possibilities by their FQCN to retain semi-predictable results
158 final List<DataContainerCodecPrototype<?>> list = new ArrayList<>(e.getValue());
159 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
160 ambiguousByCaseBuilder.putAll(e.getKey(), list);
162 unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
165 byCaseChildClass = unambiguousByCaseBuilder.build();
167 // Setup ambiguous tracking, if needed
168 ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
169 ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
170 : ConcurrentHashMap.newKeySet();
172 final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
174 * Walks all cases which are not directly instantiated and
175 * tries to match them to instantiated cases - represent same data as instantiated case,
176 * only case name or schema path is different. This is required due property of
177 * binding specification, that if choice is in grouping schema path location is lost,
178 * and users may use incorrect case class using copy builders.
180 for (final Class<?> substitution : potentialSubstitutions) {
181 search: for (final Entry<Class<?>, DataContainerCodecPrototype<?>> real : byClassBuilder.entrySet()) {
182 if (BindingReflections.isSubstitutionFor(substitution, real.getKey())) {
183 bySubstitutionBuilder.put(substitution, real.getValue());
188 byClassBuilder.putAll(bySubstitutionBuilder);
189 byClass = ImmutableMap.copyOf(byClassBuilder);
192 @SuppressWarnings("unchecked")
194 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
195 final DataContainerCodecPrototype<?> child = byClass.get(childClass);
196 return (DataContainerCodecContext<C, ?>) childNonNull(child, childClass,
197 "Supplied class %s is not valid case in %s", childClass, bindingArg()).get();
200 @SuppressWarnings("unchecked")
202 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
203 final Class<C> childClass) {
204 final DataContainerCodecPrototype<?> child = byClass.get(childClass);
206 return Optional.of((DataContainerCodecContext<C, ?>) child.get());
208 return Optional.empty();
211 Iterable<Class<?>> getCaseChildrenClasses() {
212 return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
215 protected DataContainerCodecPrototype<CaseSchemaNode> loadCase(final Class<?> childClass) {
216 final Optional<CaseSchemaNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(),
218 if (childSchema.isPresent()) {
219 return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
222 LOG.debug("Supplied class {} is not valid case in schema {}", childClass, getSchema());
227 public NodeCodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
228 final DataContainerCodecPrototype<?> cazeProto;
229 if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
230 cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
232 cazeProto = byYangCaseChild.get(arg);
235 return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
236 .yangPathArgumentChild(arg);
239 @SuppressWarnings("unchecked")
241 public D deserialize(final NormalizedNode<?, ?> data) {
242 checkArgument(data instanceof ChoiceNode);
243 final ChoiceNode casted = (ChoiceNode) data;
244 final NormalizedNode<?, ?> first = Iterables.getFirst(casted.getValue(), null);
247 // FIXME: this needs to be sorted out
250 final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
251 return (D) caze.get().deserialize(data);
255 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
256 return deserialize(normalizedNode);
260 public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
261 checkArgument(getDomPathArgument().equals(arg));
266 public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
267 // FIXME: check for null, since binding container is null.
268 return getDomPathArgument();
271 DataContainerCodecContext<?, ?> getCaseByChildClass(final @NonNull Class<? extends DataObject> type) {
272 DataContainerCodecPrototype<?> result = byCaseChildClass.get(type);
273 if (result == null) {
274 // We have not found an unambiguous result, try ambiguous ones
275 final List<DataContainerCodecPrototype<?>> inexact = ambiguousByCaseChildClass.get(type);
276 if (!inexact.isEmpty()) {
277 result = inexact.get(0);
278 // Issue a warning, but only once so as not to flood the logs
279 if (ambiguousByCaseChildWarnings.add(type)) {
280 LOG.warn("Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping "
281 + "is not guaranteed to be stable and is subject to variations based on runtime "
282 + "circumstances. Please see the stack trace for hints about the source of ambiguity.",
283 type, bindingArg(), result.getBindingClass(),
284 Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
289 return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();