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