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.model.api.AugmentationSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
47 final class ChoiceNodeCodecContext<D extends DataObject> extends DataContainerCodecContext<D, ChoiceSchemaNode> {
48 private static final Logger LOG = LoggerFactory.getLogger(ChoiceNodeCodecContext.class);
49 private final ImmutableMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChild;
52 * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence
61 * we will see {@code Baz extends ChildOf<Foo>}, which is how the users would address it in InstanceIdentifier
62 * terms. The implicit assumption being made is that {@code Baz} identifies a particular instantiation and hence
63 * provides unambiguous reference to an effective schema statement.
66 * Unfortunately this does not quite work with groupings, as their generation has changed: we do not have
67 * interfaces that would capture grouping instantiations, hence we do not have a proper addressing point and
68 * users need to specify the interfaces generated in the grouping's definition. These can be very much
69 * ambiguous, as a {@code grouping} can be used in multiple modules independently within an {@code augment}
70 * targeting {@code choice}, as each instantiation is guaranteed to have a unique namespace -- but we do not
71 * have the appropriate instantiations of those nodes.
74 * To address this issue we have a two-class lookup mechanism, which relies on the interface generated for
75 * the {@code case} statement to act as the namespace anchor bridging the nodes inside the grouping to the
76 * namespace in which they are instantiated.
79 * Furthermore downstream code relies on historical mechanics, which would guess what the instantiation is,
80 * silently assuming the ambiguity is theoretical and does not occur in practice.
83 * This leads to three classes of addressing, in order descending performance requirements.
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>
90 * {@code byCaseChildClass} supports direct DataObject mapping and contains only unambiguous children, while
91 * {@code byClass} supports indirect mapping and contains {@code case} sub-statements.
93 * ambiguousByCaseChildClass contains ambiguous mappings, for which we end up issuing warnings. We track each
94 * ambiguous reference and issue warnings when they are encountered.
96 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byClass;
97 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byCaseChildClass;
98 private final ImmutableListMultimap<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseChildClass;
99 private final Set<Class<?>> ambiguousByCaseChildWarnings;
101 ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
103 final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
105 final Map<Class<?>, DataContainerCodecPrototype<?>> byClassBuilder = new HashMap<>();
106 final SetMultimap<Class<?>, DataContainerCodecPrototype<?>> childToCase = SetMultimapBuilder.hashKeys()
107 .hashSetValues().build();
108 final Set<Class<?>> potentialSubstitutions = new HashSet<>();
109 // Walks all cases for supplied choice in current runtime context
110 for (final Class<?> caze : factory().getRuntimeContext().getCases(getBindingClass())) {
111 // We try to load case using exact match thus name
112 // and original schema must equals
113 final DataContainerCodecPrototype<CaseSchemaNode> cazeDef = loadCase(caze);
114 // If we have case definition, this case is instantiated
115 // at current location and thus is valid in context of parent choice
116 if (cazeDef != null) {
117 byClassBuilder.put(cazeDef.getBindingClass(), cazeDef);
118 // Updates collection of case children
119 @SuppressWarnings("unchecked")
120 final Class<? extends DataObject> cazeCls = (Class<? extends DataObject>) caze;
121 for (final Class<? extends DataObject> cazeChild : BindingReflections.getChildrenClasses(cazeCls)) {
122 childToCase.put(cazeChild, cazeDef);
124 // Updates collection of YANG instance identifier to case
125 for (final DataSchemaNode cazeChild : cazeDef.getSchema().getChildNodes()) {
126 if (cazeChild.isAugmenting()) {
127 final AugmentationSchemaNode augment = SchemaUtils.findCorrespondingAugment(cazeDef.getSchema(),
129 if (augment != null) {
130 byYangCaseChildBuilder.put(SchemaUtils.getNodeIdentifierForAugmentation(augment), cazeDef);
134 byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
138 * If case definition is not available, we store it for
139 * later check if it could be used as substitution of existing one.
141 potentialSubstitutions.add(caze);
144 byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
146 // Move unambiguous child->case mappings to byCaseChildClass, removing them from childToCase
147 final ImmutableListMultimap.Builder<Class<?>, DataContainerCodecPrototype<?>> ambiguousByCaseBuilder =
148 ImmutableListMultimap.builder();
149 final Builder<Class<?>, DataContainerCodecPrototype<?>> unambiguousByCaseBuilder = ImmutableMap.builder();
150 for (Entry<Class<?>, Set<DataContainerCodecPrototype<?>>> e : Multimaps.asMap(childToCase).entrySet()) {
151 final Set<DataContainerCodecPrototype<?>> cases = e.getValue();
152 if (cases.size() != 1) {
153 // Sort all possibilities by their FQCN to retain semi-predictable results
154 final List<DataContainerCodecPrototype<?>> list = new ArrayList<>(e.getValue());
155 list.sort(Comparator.comparing(proto -> proto.getBindingClass().getCanonicalName()));
156 ambiguousByCaseBuilder.putAll(e.getKey(), list);
158 unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
161 byCaseChildClass = unambiguousByCaseBuilder.build();
163 // Setup ambiguous tracking, if needed
164 ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
165 ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
166 : ConcurrentHashMap.newKeySet();
168 final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
170 * Walks all cases which are not directly instantiated and
171 * tries to match them to instantiated cases - represent same data as instantiated case,
172 * only case name or schema path is different. This is required due property of
173 * binding specification, that if choice is in grouping schema path location is lost,
174 * and users may use incorrect case class using copy builders.
176 for (final Class<?> substitution : potentialSubstitutions) {
177 search: for (final Entry<Class<?>, DataContainerCodecPrototype<?>> real : byClassBuilder.entrySet()) {
178 if (BindingReflections.isSubstitutionFor(substitution, real.getKey())) {
179 bySubstitutionBuilder.put(substitution, real.getValue());
184 byClassBuilder.putAll(bySubstitutionBuilder);
185 byClass = ImmutableMap.copyOf(byClassBuilder);
188 @SuppressWarnings("unchecked")
190 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
191 final DataContainerCodecPrototype<?> child = byClass.get(childClass);
192 return (DataContainerCodecContext<C, ?>) childNonNull(child, childClass,
193 "Supplied class %s is not valid case in %s", childClass, bindingArg()).get();
196 @SuppressWarnings("unchecked")
198 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
199 final Class<C> childClass) {
200 final DataContainerCodecPrototype<?> child = byClass.get(childClass);
202 return Optional.of((DataContainerCodecContext<C, ?>) child.get());
204 return Optional.empty();
207 Iterable<Class<?>> getCaseChildrenClasses() {
208 return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
211 protected DataContainerCodecPrototype<CaseSchemaNode> loadCase(final Class<?> childClass) {
212 final Optional<CaseSchemaNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(),
214 if (childSchema.isPresent()) {
215 return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
218 LOG.debug("Supplied class {} is not valid case in schema {}", childClass, getSchema());
223 public NodeCodecContext<?> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
224 final DataContainerCodecPrototype<?> cazeProto;
225 if (arg instanceof YangInstanceIdentifier.NodeIdentifierWithPredicates) {
226 cazeProto = byYangCaseChild.get(new NodeIdentifier(arg.getNodeType()));
228 cazeProto = byYangCaseChild.get(arg);
231 return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
232 .yangPathArgumentChild(arg);
235 @SuppressWarnings("unchecked")
237 public D deserialize(final NormalizedNode<?, ?> data) {
238 checkArgument(data instanceof ChoiceNode);
239 final ChoiceNode casted = (ChoiceNode) data;
240 final NormalizedNode<?, ?> first = Iterables.getFirst(casted.getValue(), null);
243 // FIXME: this needs to be sorted out
246 final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
247 return (D) caze.get().deserialize(data);
251 protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
252 return deserialize(normalizedNode);
256 public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
257 checkArgument(getDomPathArgument().equals(arg));
262 public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
263 // FIXME: check for null, since binding container is null.
264 return getDomPathArgument();
267 DataContainerCodecContext<?, ?> getCaseByChildClass(final @NonNull Class<? extends DataObject> type) {
268 DataContainerCodecPrototype<?> result = byCaseChildClass.get(type);
269 if (result == null) {
270 // We have not found an unambiguous result, try ambiguous ones
271 final List<DataContainerCodecPrototype<?>> inexact = ambiguousByCaseChildClass.get(type);
272 if (!inexact.isEmpty()) {
273 result = inexact.get(0);
274 // Issue a warning, but only once so as not to flood the logs
275 if (ambiguousByCaseChildWarnings.add(type)) {
276 LOG.warn("Ambiguous reference {} to child of {} resolved to {}, the first case in {} This mapping "
277 + "is not guaranteed to be stable and is subject to variations based on runtime "
278 + "circumstances. Please see the stack trace for hints about the source of ambiguity.",
279 type, bindingArg(), result.getBindingClass(),
280 Lists.transform(inexact, DataContainerCodecPrototype::getBindingClass), new Throwable());
285 return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();