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