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