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