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