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