Enable spotbugs in mdsal-binding-dom-codec
[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 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;
46
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;
50
51     /*
52      * This is a bit tricky. DataObject addressing does not take into account choice/case statements, and hence
53      * given:
54      *
55      * container foo {
56      *     choice bar {
57      *         leaf baz;
58      *     }
59      * }
60      *
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.
64      *
65      * <p>
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.
72      *
73      * <p>
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.
77      *
78      * <p>
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.
81      *
82      * <p>
83      * This leads to three classes of addressing, in order descending performance requirements.
84      * <ul>
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>
88      * </ul>
89      *
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.
92      *
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.
95      */
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;
100
101     ChoiceNodeCodecContext(final DataContainerCodecPrototype<ChoiceSchemaNode> prototype) {
102         super(prototype);
103         final Map<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangCaseChildBuilder =
104                 new HashMap<>();
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);
123                 }
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(),
128                             cazeChild);
129                         if (augment != null) {
130                             byYangCaseChildBuilder.put(SchemaUtils.getNodeIdentifierForAugmentation(augment), cazeDef);
131                             continue;
132                         }
133                     }
134                     byYangCaseChildBuilder.put(NodeIdentifier.create(cazeChild.getQName()), cazeDef);
135                 }
136             } else {
137                 /*
138                  * If case definition is not available, we store it for
139                  * later check if it could be used as substitution of existing one.
140                  */
141                 potentialSubstitutions.add(caze);
142             }
143         }
144         byYangCaseChild = ImmutableMap.copyOf(byYangCaseChildBuilder);
145
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);
157             } else {
158                 unambiguousByCaseBuilder.put(e.getKey(), cases.iterator().next());
159             }
160         }
161         byCaseChildClass = unambiguousByCaseBuilder.build();
162
163         // Setup ambiguous tracking, if needed
164         ambiguousByCaseChildClass = ambiguousByCaseBuilder.build();
165         ambiguousByCaseChildWarnings = ambiguousByCaseChildClass.isEmpty() ? ImmutableSet.of()
166                 : ConcurrentHashMap.newKeySet();
167
168         final Map<Class<?>, DataContainerCodecPrototype<?>> bySubstitutionBuilder = new HashMap<>();
169         /*
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.
175          */
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());
180                     break search;
181                 }
182             }
183         }
184         byClassBuilder.putAll(bySubstitutionBuilder);
185         byClass = ImmutableMap.copyOf(byClassBuilder);
186     }
187
188     @SuppressWarnings("unchecked")
189     @Override
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();
194     }
195
196     @SuppressWarnings("unchecked")
197     @Override
198     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
199             final Class<C> childClass) {
200         final DataContainerCodecPrototype<?> child = byClass.get(childClass);
201         if (child != null) {
202             return Optional.of((DataContainerCodecContext<C, ?>) child.get());
203         }
204         return Optional.empty();
205     }
206
207     Iterable<Class<?>> getCaseChildrenClasses() {
208         return Iterables.concat(byCaseChildClass.keySet(), ambiguousByCaseChildClass.keySet());
209     }
210
211     protected DataContainerCodecPrototype<CaseSchemaNode> loadCase(final Class<?> childClass) {
212         final Optional<CaseSchemaNode> childSchema = factory().getRuntimeContext().getCaseSchemaDefinition(getSchema(),
213             childClass);
214         if (childSchema.isPresent()) {
215             return DataContainerCodecPrototype.from(childClass, childSchema.get(), factory());
216         }
217
218         LOG.debug("Supplied class {} is not valid case in schema {}", childClass, getSchema());
219         return null;
220     }
221
222     @Override
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()));
227         } else {
228             cazeProto = byYangCaseChild.get(arg);
229         }
230
231         return childNonNull(cazeProto, arg, "Argument %s is not valid child of %s", arg, getSchema()).get()
232                 .yangPathArgumentChild(arg);
233     }
234
235     @SuppressWarnings("unchecked")
236     @Override
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);
241
242         if (first == null) {
243             // FIXME: this needs to be sorted out
244             return null;
245         }
246         final DataContainerCodecPrototype<?> caze = byYangCaseChild.get(first.getIdentifier());
247         return (D) caze.get().deserialize(data);
248     }
249
250     @Override
251     protected Object deserializeObject(final NormalizedNode<?, ?> normalizedNode) {
252         return deserialize(normalizedNode);
253     }
254
255     @Override
256     public PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
257         checkArgument(getDomPathArgument().equals(arg));
258         return null;
259     }
260
261     @Override
262     public YangInstanceIdentifier.PathArgument serializePathArgument(final PathArgument arg) {
263         // FIXME: check for null, since binding container is null.
264         return getDomPathArgument();
265     }
266
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());
281                 }
282             }
283         }
284
285         return childNonNull(result, type, "Class %s is not child of any cases for %s", type, bindingArg()).get();
286     }
287 }