2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
10 import static java.util.Objects.requireNonNull;
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;
25 import java.util.Optional;
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;
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;
66 EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
67 "eventStreamSerializer", DataObjectSerializer.class);
68 } catch (NoSuchFieldException | IllegalAccessException e) {
69 throw new ExceptionInInitializerError(e);
73 final @NonNull DataContainerCodecPrototype<T> prototype;
75 // Accessed via a VarHandle
76 @SuppressWarnings("unused")
77 private volatile DataObjectSerializer eventStreamSerializer;
79 DataContainerCodecContext(final DataContainerCodecPrototype<T> prototype) {
80 this.prototype = requireNonNull(prototype);
83 public final @NonNull T getType() {
84 return prototype.getType();
88 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
89 return prototype.getChildAddressabilitySummary();
92 protected final QNameModule namespace() {
93 return prototype.getNamespace();
96 protected final CodecContextFactory factory() {
97 return prototype.getFactory();
101 protected NodeIdentifier getDomPathArgument() {
102 return prototype.getYangArg();
106 * Returns nested node context using supplied YANG Instance Identifier.
108 * @param arg Yang Instance Identifier Argument
109 * @return Context of child
110 * @throws IllegalArgumentException If supplied argument does not represent valid child.
113 public abstract CodecContext yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg);
116 * Returns nested node context using supplied Binding Instance Identifier
117 * and adds YANG instance identifiers to supplied list.
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.
124 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
125 final List<YangInstanceIdentifier.PathArgument> builder) {
126 final var child = streamChild(arg.getType());
127 child.addYangPathArgument(arg, builder);
132 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
134 * @param arg Binding Path Argument
135 * @param builder DOM Path argument.
137 final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
138 if (builder != null) {
139 addYangPathArgument(builder, arg);
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);
151 * Returns deserialized Binding Path Argument from YANG instance identifier.
153 protected PathArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) {
157 protected final PathArgument bindingArg() {
158 return prototype.getBindingArg();
161 @SuppressWarnings("unchecked")
163 public final Class<D> getBindingClass() {
164 return Class.class.cast(prototype.getBindingClass());
168 public abstract <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(Class<C> childClass);
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).
174 * @param childClass child class
175 * @return Context of child or Optional.empty is supplied class is not applicable in context.
178 public abstract <C extends DataObject> Optional<DataContainerCodecContext<C,?>> possibleStreamChild(
179 Class<C> childClass);
182 public String toString() {
183 return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
186 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?> & BindingNormalizedNodeCodec<T>>
187 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
188 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
189 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
190 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
193 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
194 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
195 if (nullable == null) {
196 throw childNullException(child.getNodeType(), message, args);
201 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
202 final Object... args) {
203 if (nullable == null) {
204 throw childNullException(child, message, args);
209 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
210 final String message, final Object... args) {
211 if (nullable == null) {
212 throw childNullException(childClass, message, args);
218 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
219 final QNameModule module = child.getModule();
220 if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
221 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
223 return new IncorrectNestingException(message, args);
227 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
228 final Object... args) {
229 return childNullException(factory().getRuntimeContext(), childClass, message, args);
233 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
234 final Class<?> childClass, final String message, final Object... args) {
235 final CompositeRuntimeType schema;
236 if (Augmentation.class.isAssignableFrom(childClass)) {
237 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
239 schema = runtimeContext.getSchemaDefinition(childClass);
241 if (schema == null) {
242 return new MissingSchemaForClassException(childClass);
246 runtimeContext.loadClass(Type.of(childClass));
247 } catch (final ClassNotFoundException e) {
248 return new MissingClassInLoadingStrategyException(
249 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
252 return new IncorrectNestingException(message, args);
255 final DataObjectSerializer eventStreamSerializer() {
256 final DataObjectSerializer existing = (DataObjectSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
257 return existing != null ? existing : loadEventStreamSerializer();
260 // Split out to aid inlining
261 private DataObjectSerializer loadEventStreamSerializer() {
262 final DataObjectSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
263 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
264 return witness == null ? loaded : (DataObjectSerializer) witness;
267 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
268 final var result = new NormalizationResultHolder();
269 // We create DOM stream writer which produces normalized nodes
270 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
272 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
273 } catch (final IOException e) {
274 throw new IllegalStateException("Failed to serialize Binding DTO",e);
276 return result.getResult().data();
279 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
280 final NormalizedNode data) {
282 return expectedType.cast(requireNonNull(data));
283 } catch (ClassCastException e) {
284 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
288 // FIXME: MDSAL-780 replace this method with BindingRuntimeTypes-driven logic
289 static final Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
290 final String prefix) {
291 final String methodName = method.getName();
292 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
293 return Optional.empty();
296 final Class<?> returnType = method.getReturnType();
297 if (DataContainer.class.isAssignableFrom(returnType)) {
298 return optionalDataContainer(returnType);
299 } else if (List.class.isAssignableFrom(returnType)) {
300 return getYangModeledReturnType(method, 0);
301 } else if (Map.class.isAssignableFrom(returnType)) {
302 return getYangModeledReturnType(method, 1);
304 return Optional.empty();
307 @SuppressWarnings("checkstyle:illegalCatch")
308 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
309 final int parameterOffset) {
311 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(),
312 () -> genericParameter(method.getGenericReturnType(), parameterOffset)
313 .flatMap(result -> result instanceof Class ? optionalCast((Class<?>) result) : Optional.empty()));
314 } catch (Exception e) {
316 * It is safe to log this this exception on debug, since this
317 * method should not fail. Only failures are possible if the
320 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
322 return Optional.empty();
325 private static Optional<java.lang.reflect.Type> genericParameter(final java.lang.reflect.Type type,
327 if (type instanceof ParameterizedType parameterized) {
328 final var parameters = parameterized.getActualTypeArguments();
329 if (parameters.length > offset) {
330 return Optional.of(parameters[offset]);
333 return Optional.empty();
336 private static Optional<Class<? extends DataContainer>> optionalCast(final Class<?> type) {
337 return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty();
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));
346 * Determines if two augmentation classes or case classes represents same data.
349 * Two augmentations or cases could be substituted only if and if:
351 * <li>Both implements same interfaces</li>
352 * <li>Both have same children</li>
353 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
355 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
359 * <b>Explanation:</b>
360 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
361 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
362 * augmentation in particular subtree (via copy constructors, etc).
364 * @param potential Class which is potential substitution
365 * @param target Class which should be used at particular subtree
366 * @return true if and only if classes represents same data.
367 * @throws NullPointerException if any argument is {@code null}
369 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
370 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
371 // a particular world this boils down to a matrix, which can be calculated either on-demand or
372 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
373 // to have a pre-compiled Binding Runtime.
374 @SuppressWarnings({ "rawtypes", "unchecked" })
375 static final boolean isSubstitutionFor(final Class potential, final Class target) {
376 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
377 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
378 if (!subImplemented.equals(targetImplemented)) {
381 if (Augmentation.class.isAssignableFrom(potential)
382 && !BindingReflections.findAugmentationTarget(potential).equals(
383 BindingReflections.findAugmentationTarget(target))) {
386 for (Method potentialMethod : potential.getMethods()) {
387 if (Modifier.isStatic(potentialMethod.getModifiers())) {
388 // Skip any static methods, as we are not interested in those
393 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
394 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
397 } catch (NoSuchMethodException e) {
398 // Counterpart method is missing, so classes could not be substituted.
400 } catch (SecurityException e) {
401 throw new IllegalStateException("Could not compare methods", e);