Hide CodecContext methods
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataContainerCodecContext.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 java.util.Objects.requireNonNull;
11
12 import com.google.common.collect.ImmutableCollection;
13 import com.google.common.collect.ImmutableSet;
14 import edu.umd.cs.findbugs.annotations.CheckReturnValue;
15 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.IOException;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.VarHandle;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Modifier;
21 import java.util.Arrays;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Optional;
25 import java.util.Set;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataContainerCodecTreeNode;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCodec;
31 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
32 import org.opendaylight.mdsal.binding.dom.codec.api.MissingClassInLoadingStrategyException;
33 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaException;
34 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaForClassException;
35 import org.opendaylight.mdsal.binding.model.api.Type;
36 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
37 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
38 import org.opendaylight.yangtools.util.ClassLoaderUtils;
39 import org.opendaylight.yangtools.yang.binding.Augmentable;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.binding.BindingObject;
42 import org.opendaylight.yangtools.yang.binding.DataContainer;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.DataObjectStep;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
52 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 abstract sealed class DataContainerCodecContext<D extends DataContainer, R extends CompositeRuntimeType,
66         P extends DataContainerPrototype<?, R>>
67         extends CodecContext implements BindingDataContainerCodecTreeNode<D>
68         permits ChoiceCodecContext, CommonDataObjectCodecContext {
69     private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecContext.class);
70     private static final VarHandle EVENT_STREAM_SERIALIZER;
71
72     static {
73         try {
74             EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
75                 "eventStreamSerializer", DataContainerSerializer.class);
76         } catch (NoSuchFieldException | IllegalAccessException e) {
77             throw new ExceptionInInitializerError(e);
78         }
79     }
80
81     private final @NonNull P prototype;
82     private final @NonNull ChildAddressabilitySummary childAddressabilitySummary;
83
84     // Accessed via a VarHandle
85     @SuppressWarnings("unused")
86     @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
87     private volatile DataContainerSerializer eventStreamSerializer;
88
89     DataContainerCodecContext(final P prototype) {
90         this.prototype = requireNonNull(prototype);
91         childAddressabilitySummary = computeChildAddressabilitySummary(prototype.runtimeType().statement());
92     }
93
94     final @NonNull P prototype() {
95         return prototype;
96     }
97
98     @Override
99     @SuppressWarnings("unchecked")
100     public final Class<D> getBindingClass() {
101         return (Class<D>) prototype().javaClass();
102     }
103
104     // overridden in AugmentationCodecContext
105     @Override
106     NodeIdentifier getDomPathArgument() {
107         return prototype.yangArg();
108     }
109
110     @Override
111     public final ChildAddressabilitySummary getChildAddressabilitySummary() {
112         return childAddressabilitySummary;
113     }
114
115     // Non-final for ChoiceCodecContext
116     @Override
117     public CodecContext yangPathArgumentChild(final PathArgument arg) {
118         CodecContextSupplier supplier;
119         if (arg instanceof NodeIdentifier nodeId) {
120             supplier = yangChildSupplier(nodeId);
121         } else if (arg instanceof NodeIdentifierWithPredicates nip) {
122             supplier = yangChildSupplier(new NodeIdentifier(nip.getNodeType()));
123         } else {
124             supplier = null;
125         }
126         return childNonNull(supplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).getCodecContext();
127     }
128
129     abstract @Nullable CodecContextSupplier yangChildSupplier(@NonNull NodeIdentifier arg);
130
131     @Override
132     public abstract CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(DataObjectStep<?> step,
133         List<PathArgument> builder);
134
135     /**
136      * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
137      *
138      * @param step Binding Path Argument
139      * @param builder DOM Path argument.
140      */
141     final void addYangPathArgument(final DataObjectStep<?> step, final List<PathArgument> builder) {
142         if (builder != null) {
143             addYangPathArgument(builder, step);
144         }
145     }
146
147     void addYangPathArgument(final @NonNull List<PathArgument> builder, final DataObjectStep<?> step) {
148         final var yangArg = getDomPathArgument();
149         if (yangArg != null) {
150             builder.add(yangArg);
151         }
152     }
153
154     @Override
155     public final <C extends DataObject> DataContainerCodecContext<C, ?, ?> getStreamChild(final Class<C> childClass) {
156         return childNonNull(streamChild(childClass), childClass,
157             "Child %s is not valid child of %s", getBindingClass(), childClass);
158     }
159
160     @SuppressWarnings("unchecked")
161     @Override
162     public final <C extends DataObject> DataContainerCodecContext<C, ?, ?> streamChild(final Class<C> childClass) {
163         final var childProto = streamChildPrototype(requireNonNull(childClass));
164         return childProto == null ? null : (DataContainerCodecContext<C, ?, ?>) childProto.getCodecContext();
165     }
166
167     abstract @Nullable DataContainerPrototype<?, ?> streamChildPrototype(@NonNull Class<?> childClass);
168
169     @Override
170     public String toString() {
171         return getClass().getSimpleName() + " [" + getBindingClass() + "]";
172     }
173
174     static final <T extends DataObject, C extends DataContainerCodecContext<T, ?, ?> & BindingNormalizedNodeCodec<T>>
175             @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
176                 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
177         return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
178             : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
179     }
180
181     protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final PathArgument child,
182             final String message, final Object... args) {
183         if (nullable == null) {
184             throw childNullException(child.getNodeType(), message, args);
185         }
186         return nullable;
187     }
188
189     protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
190             final Object... args) {
191         if (nullable == null) {
192             throw childNullException(child, message, args);
193         }
194         return nullable;
195     }
196
197     protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
198             final String message, final Object... args) {
199         if (nullable == null) {
200             throw childNullException(childClass, message, args);
201         }
202         return nullable;
203     }
204
205     @CheckReturnValue
206     private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
207         final var module = child.getModule();
208         if (!prototype().contextFactory().getRuntimeContext().modelContext().findModule(module).isPresent()) {
209             return new MissingSchemaException("Module " + module + " is not present in current schema context.");
210         }
211         return new IncorrectNestingException(message, args);
212     }
213
214     @CheckReturnValue
215     private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
216             final Object... args) {
217         return childNullException(prototype().contextFactory().getRuntimeContext(), childClass, message, args);
218     }
219
220     @CheckReturnValue
221     static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
222             final Class<?> childClass, final String message, final Object... args) {
223         final CompositeRuntimeType schema;
224         if (Augmentation.class.isAssignableFrom(childClass)) {
225             schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
226         } else {
227             schema = runtimeContext.getSchemaDefinition(childClass);
228         }
229         if (schema == null) {
230             return new MissingSchemaForClassException(childClass);
231         }
232
233         try {
234             runtimeContext.loadClass(Type.of(childClass));
235         } catch (final ClassNotFoundException e) {
236             return new MissingClassInLoadingStrategyException(
237                 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
238         }
239
240         return new IncorrectNestingException(message, args);
241     }
242
243     final DataContainerSerializer eventStreamSerializer() {
244         final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
245         return existing != null ? existing : loadEventStreamSerializer();
246     }
247
248     // Split out to aid inlining
249     private DataContainerSerializer loadEventStreamSerializer() {
250         final DataContainerSerializer loaded = prototype().contextFactory().getEventStreamSerializer(getBindingClass());
251         final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
252         return witness == null ? loaded : (DataContainerSerializer) witness;
253     }
254
255     final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
256         final var result = new NormalizationResultHolder();
257         // We create DOM stream writer which produces normalized nodes
258         final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
259         try {
260             eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
261         } catch (final IOException e) {
262             throw new IllegalStateException("Failed to serialize Binding DTO",e);
263         }
264         return result.getResult().data();
265     }
266
267     static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
268             final NormalizedNode data) {
269         try {
270             return expectedType.cast(requireNonNull(data));
271         } catch (ClassCastException e) {
272             throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
273         }
274     }
275
276     /**
277      * Determines if two augmentation classes or case classes represents same data.
278      *
279      * <p>
280      * Two augmentations or cases could be substituted only if and if:
281      * <ul>
282      *   <li>Both implements same interfaces</li>
283      *   <li>Both have same children</li>
284      *   <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
285      *       grouping.</li>
286      *   <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
287      * </ul>
288      *
289      * <p>
290      * <b>Explanation:</b>
291      * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
292      * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
293      * augmentation in particular subtree (via copy constructors, etc).
294      *
295      * @param potential Class which is potential substitution
296      * @param target Class which should be used at particular subtree
297      * @return true if and only if classes represents same data.
298      * @throws NullPointerException if any argument is {@code null}
299      */
300     // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
301     //                   user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
302     //                   a particular world this boils down to a matrix, which can be calculated either on-demand or
303     //                   when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
304     //                   to have a pre-compiled Binding Runtime.
305     @SuppressWarnings({ "rawtypes", "unchecked" })
306     static final boolean isSubstitutionFor(final Class potential, final Class target) {
307         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
308         Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
309         if (!subImplemented.equals(targetImplemented)) {
310             return false;
311         }
312         if (Augmentation.class.isAssignableFrom(potential)
313             && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
314             return false;
315         }
316         for (Method potentialMethod : potential.getMethods()) {
317             if (Modifier.isStatic(potentialMethod.getModifiers())) {
318                 // Skip any static methods, as we are not interested in those
319                 continue;
320             }
321
322             try {
323                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
324                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
325                     return false;
326                 }
327             } catch (NoSuchMethodException e) {
328                 // Counterpart method is missing, so classes could not be substituted.
329                 return false;
330             } catch (SecurityException e) {
331                 throw new IllegalStateException("Could not compare methods", e);
332             }
333         }
334         return true;
335     }
336
337     /**
338      * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
339      * implemented {@link Augmentation} interface.
340      *
341      * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
342      * @return Augmentation target - class which augmentation provides additional extensions.
343      */
344     static final Class<? extends Augmentable<?>> findAugmentationTarget(
345             final Class<? extends Augmentation<?>> augmentation) {
346         final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
347             Augmentation.class);
348         return opt.orElse(null);
349     }
350
351     private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
352         // FIXME: rework this to work on EffectiveStatements
353         if (nodeSchema instanceof DataNodeContainer contaner) {
354             boolean haveAddressable = false;
355             boolean haveUnaddressable = false;
356             for (DataSchemaNode child : contaner.getChildNodes()) {
357                 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
358                     haveAddressable = true;
359                 } else if (child instanceof ListSchemaNode list) {
360                     if (list.getKeyDefinition().isEmpty()) {
361                         haveUnaddressable = true;
362                     } else {
363                         haveAddressable = true;
364                     }
365                 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
366                         || child instanceof TypedDataSchemaNode) {
367                     haveUnaddressable = true;
368                 } else if (child instanceof ChoiceSchemaNode choice) {
369                     switch (computeChildAddressabilitySummary(choice)) {
370                         case ADDRESSABLE -> haveAddressable = true;
371                         case UNADDRESSABLE -> haveUnaddressable = true;
372                         case MIXED -> {
373                             haveAddressable = true;
374                             haveUnaddressable = true;
375                         }
376                         default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
377                     }
378                 } else {
379                     LOG.warn("Unhandled child node {}", child);
380                 }
381             }
382
383             if (!haveAddressable) {
384                 // Empty or all are unaddressable
385                 return ChildAddressabilitySummary.UNADDRESSABLE;
386             }
387
388             return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
389         } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
390             return computeChildAddressabilitySummary(choice);
391         }
392
393         // No child nodes possible: return unaddressable
394         return ChildAddressabilitySummary.UNADDRESSABLE;
395     }
396
397     private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
398             final ChoiceSchemaNode choice) {
399         boolean haveAddressable = false;
400         boolean haveUnaddressable = false;
401         for (CaseSchemaNode child : choice.getCases()) {
402             switch (computeChildAddressabilitySummary(child)) {
403                 case ADDRESSABLE:
404                     haveAddressable = true;
405                     break;
406                 case UNADDRESSABLE:
407                     haveUnaddressable = true;
408                     break;
409                 case MIXED:
410                     // A child is mixed, which means we are mixed, too
411                     return ChildAddressabilitySummary.MIXED;
412                 default:
413                     throw new IllegalStateException("Unhandled accessibility summary for " + child);
414             }
415         }
416
417         if (!haveAddressable) {
418             // Empty or all are unaddressable
419             return ChildAddressabilitySummary.UNADDRESSABLE;
420         }
421
422         return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
423     }
424 }