Fold RootCodecContext into BindingCodecContext
[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.util.Arrays;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Optional;
24 import java.util.Set;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataContainerCodecTreeNode;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCodec;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingStreamEventWriter;
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.mdsal.binding.runtime.api.RuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.RuntimeTypeContainer;
40 import org.opendaylight.yangtools.util.ClassLoaderUtils;
41 import org.opendaylight.yangtools.yang.binding.Augmentable;
42 import org.opendaylight.yangtools.yang.binding.Augmentation;
43 import org.opendaylight.yangtools.yang.binding.BindingObject;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
52 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
53 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
65
66 abstract sealed class DataContainerCodecContext<D extends BindingObject & DataContainer, T extends RuntimeTypeContainer>
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 ChildAddressabilitySummary childAddressabilitySummary;
82
83     // Accessed via a VarHandle
84     @SuppressWarnings("unused")
85     private volatile DataContainerSerializer eventStreamSerializer;
86
87     DataContainerCodecContext(final T type) {
88         childAddressabilitySummary = type instanceof RuntimeType runtimeType
89             ? computeChildAddressabilitySummary(runtimeType.statement())
90                 // BindingRuntimeTypes, does not matter
91                 : ChildAddressabilitySummary.MIXED;
92     }
93
94     @Override
95     public final ChildAddressabilitySummary getChildAddressabilitySummary() {
96         return childAddressabilitySummary;
97     }
98
99     protected abstract @NonNull CodecContextFactory factory();
100
101     protected abstract @NonNull T type();
102
103     /**
104      * Returns nested node context using supplied YANG Instance Identifier.
105      *
106      * @param arg Yang Instance Identifier Argument
107      * @return Context of child
108      * @throws IllegalArgumentException If supplied argument does not represent valid child.
109      */
110     @Override
111     public abstract CodecContext yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg);
112
113     /**
114      * Returns nested node context using supplied Binding Instance Identifier
115      * and adds YANG instance identifiers to supplied list.
116      *
117      * @param arg Binding Instance Identifier Argument
118      * @return Context of child or null if supplied {@code arg} does not represent valid child.
119      * @throws IllegalArgumentException If supplied argument does not represent valid child.
120      */
121     @Override
122     public CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
123             final List<YangInstanceIdentifier.PathArgument> builder) {
124         final var child = getStreamChild(arg.getType());
125         child.addYangPathArgument(arg, builder);
126         return child;
127     }
128
129     /**
130      * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
131      *
132      * @param arg Binding Path Argument
133      * @param builder DOM Path argument.
134      */
135     final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
136         if (builder != null) {
137             addYangPathArgument(builder, arg);
138         }
139     }
140
141     void addYangPathArgument(final @NonNull List<YangInstanceIdentifier.PathArgument> builder, final PathArgument arg) {
142         final var yangArg = getDomPathArgument();
143         if (yangArg != null) {
144             builder.add(yangArg);
145         }
146     }
147
148     @Override
149     public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(Class<C> childClass);
150
151     /**
152      * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
153      * must issue getChild(ChoiceClass).getChild(CaseClass).
154      *
155      * @param childClass child class
156      * @return Context of child or Optional.empty is supplied class is not applicable in context.
157      */
158     @Override
159     public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(Class<C> 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 QNameModule module = child.getModule();
200         if (!factory().getRuntimeContext().getEffectiveModelContext().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(factory().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 = factory().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
344
345     private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
346         // FIXME: rework this to work on EffectiveStatements
347         if (nodeSchema instanceof DataNodeContainer contaner) {
348             boolean haveAddressable = false;
349             boolean haveUnaddressable = false;
350             for (DataSchemaNode child : contaner.getChildNodes()) {
351                 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
352                     haveAddressable = true;
353                 } else if (child instanceof ListSchemaNode list) {
354                     if (list.getKeyDefinition().isEmpty()) {
355                         haveUnaddressable = true;
356                     } else {
357                         haveAddressable = true;
358                     }
359                 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
360                         || child instanceof TypedDataSchemaNode) {
361                     haveUnaddressable = true;
362                 } else if (child instanceof ChoiceSchemaNode choice) {
363                     switch (computeChildAddressabilitySummary(choice)) {
364                         case ADDRESSABLE -> haveAddressable = true;
365                         case UNADDRESSABLE -> haveUnaddressable = true;
366                         case MIXED -> {
367                             haveAddressable = true;
368                             haveUnaddressable = true;
369                         }
370                         default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
371                     }
372                 } else {
373                     LOG.warn("Unhandled child node {}", child);
374                 }
375             }
376
377             if (!haveAddressable) {
378                 // Empty or all are unaddressable
379                 return ChildAddressabilitySummary.UNADDRESSABLE;
380             }
381
382             return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
383         } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
384             return computeChildAddressabilitySummary(choice);
385         }
386
387         // No child nodes possible: return unaddressable
388         return ChildAddressabilitySummary.UNADDRESSABLE;
389     }
390
391     private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
392             final ChoiceSchemaNode choice) {
393         boolean haveAddressable = false;
394         boolean haveUnaddressable = false;
395         for (CaseSchemaNode child : choice.getCases()) {
396             switch (computeChildAddressabilitySummary(child)) {
397                 case ADDRESSABLE:
398                     haveAddressable = true;
399                     break;
400                 case UNADDRESSABLE:
401                     haveUnaddressable = true;
402                     break;
403                 case MIXED:
404                     // A child is mixed, which means we are mixed, too
405                     return ChildAddressabilitySummary.MIXED;
406                 default:
407                     throw new IllegalStateException("Unhandled accessibility summary for " + child);
408             }
409         }
410
411         if (!haveAddressable) {
412             // Empty or all are unaddressable
413             return ChildAddressabilitySummary.UNADDRESSABLE;
414         }
415
416         return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
417     }
418 }