Remove BindingDataObjectCodecTreeNode.writeAsNormalizedNode()
[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 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.BindingDataObjectCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingStreamEventWriter;
32 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
33 import org.opendaylight.mdsal.binding.dom.codec.api.MissingClassInLoadingStrategyException;
34 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaException;
35 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaForClassException;
36 import org.opendaylight.mdsal.binding.model.api.Type;
37 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
38 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.RuntimeTypeContainer;
40 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
41 import org.opendaylight.yangtools.util.ClassLoaderUtils;
42 import org.opendaylight.yangtools.yang.binding.Augmentation;
43 import org.opendaylight.yangtools.yang.binding.BindingObject;
44 import org.opendaylight.yangtools.yang.binding.DataContainer;
45 import org.opendaylight.yangtools.yang.binding.DataObject;
46 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.common.QNameModule;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
50 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
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 BindingDataObjectCodecTreeNode<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     private 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 final YangInstanceIdentifier.PathArgument 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             builder.add(getDomPathArgument());
141         }
142     }
143
144     /**
145      * Returns deserialized Binding Path Argument from YANG instance identifier.
146      */
147     protected PathArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) {
148         return bindingArg();
149     }
150
151     protected final PathArgument bindingArg() {
152         return prototype.getBindingArg();
153     }
154
155     @SuppressWarnings("unchecked")
156     @Override
157     public final Class<D> getBindingClass() {
158         return Class.class.cast(prototype.getBindingClass());
159     }
160
161     @Override
162     public abstract <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(Class<C> childClass);
163
164     /**
165      * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
166      * must issue getChild(ChoiceClass).getChild(CaseClass).
167      *
168      * @param childClass child class
169      * @return Context of child or Optional.empty is supplied class is not applicable in context.
170      */
171     @Override
172     public abstract <C extends DataObject> Optional<DataContainerCodecContext<C,?>> possibleStreamChild(
173             Class<C> childClass);
174
175     @Override
176     public String toString() {
177         return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
178     }
179
180     @Override
181     public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
182             final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
183         if (cacheSpecifier.isEmpty()) {
184             return new NonCachingCodec<>(this);
185         }
186         return new CachingNormalizedNodeCodec<>(this, 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(extractName(child), 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     private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
214         final QNameModule module = child.getModule();
215         if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
216             throw new MissingSchemaException("Module " + module + " is not present in current schema context.");
217         }
218         throw IncorrectNestingException.create(message, args);
219     }
220
221     private IllegalArgumentException childNullException(final Class<?> childClass, final String message,
222             final Object... args) {
223         final BindingRuntimeContext runtimeContext = factory().getRuntimeContext();
224         final CompositeRuntimeType schema;
225         if (Augmentation.class.isAssignableFrom(childClass)) {
226             schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
227         } else {
228             schema = runtimeContext.getSchemaDefinition(childClass);
229         }
230         if (schema == null) {
231             throw new MissingSchemaForClassException(childClass);
232         }
233
234         try {
235             runtimeContext.loadClass(Type.of(childClass));
236         } catch (final ClassNotFoundException e) {
237             throw new MissingClassInLoadingStrategyException(
238                 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
239         }
240
241         throw IncorrectNestingException.create(message, args);
242     }
243
244     private static QName extractName(final YangInstanceIdentifier.PathArgument child) {
245         if (child instanceof AugmentationIdentifier) {
246             final Set<QName> children = ((AugmentationIdentifier) child).getPossibleChildNames();
247             checkArgument(!children.isEmpty(), "Augmentation without childs must not be used in data");
248             return children.iterator().next();
249         }
250         return child.getNodeType();
251     }
252
253     final DataObjectSerializer eventStreamSerializer() {
254         final DataObjectSerializer existing = (DataObjectSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
255         return existing != null ? existing : loadEventStreamSerializer();
256     }
257
258     // Split out to aid inlining
259     private DataObjectSerializer loadEventStreamSerializer() {
260         final DataObjectSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
261         final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
262         return witness == null ? loaded : (DataObjectSerializer) witness;
263     }
264
265     @Override
266     public NormalizedNode serialize(final D data) {
267         final NormalizedNodeResult result = new NormalizedNodeResult();
268         // We create DOM stream writer which produces normalized nodes
269         final NormalizedNodeStreamWriter 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();
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
340     // FIXME: MDSAL-780: remove this method
341     static final Optional<Class<? extends DataContainer>> optionalDataContainer(final Class<?> type) {
342         return Optional.of(type.asSubclass(DataContainer.class));
343     }
344
345
346     /**
347      * Determines if two augmentation classes or case classes represents same data.
348      *
349      * <p>
350      * Two augmentations or cases could be substituted only if and if:
351      * <ul>
352      *   <li>Both implements same interfaces</li>
353      *   <li>Both have same children</li>
354      *   <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
355      *       grouping.</li>
356      *   <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
357      * </ul>
358      *
359      * <p>
360      * <b>Explanation:</b>
361      * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
362      * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
363      * augmentation in particular subtree (via copy constructors, etc).
364      *
365      * @param potential Class which is potential substitution
366      * @param target Class which should be used at particular subtree
367      * @return true if and only if classes represents same data.
368      * @throws NullPointerException if any argument is {@code null}
369      */
370     // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
371     //                   user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
372     //                   a particular world this boils down to a matrix, which can be calculated either on-demand or
373     //                   when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
374     //                   to have a pre-compiled Binding Runtime.
375     @SuppressWarnings({ "rawtypes", "unchecked" })
376     static boolean isSubstitutionFor(final Class potential, final Class target) {
377         Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
378         Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
379         if (!subImplemented.equals(targetImplemented)) {
380             return false;
381         }
382         if (Augmentation.class.isAssignableFrom(potential)
383                 && !BindingReflections.findAugmentationTarget(potential).equals(
384                         BindingReflections.findAugmentationTarget(target))) {
385             return false;
386         }
387         for (Method potentialMethod : potential.getMethods()) {
388             if (Modifier.isStatic(potentialMethod.getModifiers())) {
389                 // Skip any static methods, as we are not interested in those
390                 continue;
391             }
392
393             try {
394                 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
395                 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
396                     return false;
397                 }
398             } catch (NoSuchMethodException e) {
399                 // Counterpart method is missing, so classes could not be substituted.
400                 return false;
401             } catch (SecurityException e) {
402                 throw new IllegalStateException("Could not compare methods", e);
403             }
404         }
405         return true;
406     }
407 }