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