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