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