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