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.BindingDataContainerCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCodec;
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.RuntimeType;
41 import org.opendaylight.mdsal.binding.runtime.api.RuntimeTypeContainer;
42 import org.opendaylight.yangtools.util.ClassLoaderUtils;
43 import org.opendaylight.yangtools.yang.binding.Augmentable;
44 import org.opendaylight.yangtools.yang.binding.Augmentation;
45 import org.opendaylight.yangtools.yang.binding.BindingObject;
46 import org.opendaylight.yangtools.yang.binding.DataContainer;
47 import org.opendaylight.yangtools.yang.binding.DataObject;
48 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.common.QName;
50 import org.opendaylight.yangtools.yang.common.QNameModule;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
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.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
62 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
63 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
68 abstract sealed class DataContainerCodecContext<D extends BindingObject & DataContainer, T extends RuntimeTypeContainer>
69 extends CodecContext implements BindingDataContainerCodecTreeNode<D>
70 permits CommonDataObjectCodecContext, RootCodecContext {
71 private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecContext.class);
72 private static final VarHandle EVENT_STREAM_SERIALIZER;
76 EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
77 "eventStreamSerializer", DataContainerSerializer.class);
78 } catch (NoSuchFieldException | IllegalAccessException e) {
79 throw new ExceptionInInitializerError(e);
83 private final @NonNull ChildAddressabilitySummary childAddressabilitySummary;
85 // Accessed via a VarHandle
86 @SuppressWarnings("unused")
87 private volatile DataContainerSerializer eventStreamSerializer;
89 DataContainerCodecContext(final T type) {
90 childAddressabilitySummary = type instanceof RuntimeType runtimeType
91 ? computeChildAddressabilitySummary(runtimeType.statement())
92 // BindingRuntimeTypes, does not matter
93 : ChildAddressabilitySummary.MIXED;
97 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
98 return childAddressabilitySummary;
101 protected abstract @NonNull CodecContextFactory factory();
103 protected abstract @NonNull T type();
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 CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
125 final List<YangInstanceIdentifier.PathArgument> builder) {
126 final var child = getStreamChild(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 public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(Class<C> childClass);
154 * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
155 * must issue getChild(ChoiceClass).getChild(CaseClass).
157 * @param childClass child class
158 * @return Context of child or Optional.empty is supplied class is not applicable in context.
161 public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(Class<C> childClass);
164 public String toString() {
165 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
168 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?> & BindingNormalizedNodeCodec<T>>
169 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
170 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
171 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
172 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
175 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
176 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
177 if (nullable == null) {
178 throw childNullException(child.getNodeType(), message, args);
183 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
184 final Object... args) {
185 if (nullable == null) {
186 throw childNullException(child, message, args);
191 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
192 final String message, final Object... args) {
193 if (nullable == null) {
194 throw childNullException(childClass, message, args);
200 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
201 final QNameModule module = child.getModule();
202 if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
203 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
205 return new IncorrectNestingException(message, args);
209 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
210 final Object... args) {
211 return childNullException(factory().getRuntimeContext(), childClass, message, args);
215 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
216 final Class<?> childClass, final String message, final Object... args) {
217 final CompositeRuntimeType schema;
218 if (Augmentation.class.isAssignableFrom(childClass)) {
219 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
221 schema = runtimeContext.getSchemaDefinition(childClass);
223 if (schema == null) {
224 return new MissingSchemaForClassException(childClass);
228 runtimeContext.loadClass(Type.of(childClass));
229 } catch (final ClassNotFoundException e) {
230 return new MissingClassInLoadingStrategyException(
231 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
234 return new IncorrectNestingException(message, args);
237 final DataContainerSerializer eventStreamSerializer() {
238 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
239 return existing != null ? existing : loadEventStreamSerializer();
242 // Split out to aid inlining
243 private DataContainerSerializer loadEventStreamSerializer() {
244 final DataContainerSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
245 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
246 return witness == null ? loaded : (DataContainerSerializer) witness;
249 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
250 final var result = new NormalizationResultHolder();
251 // We create DOM stream writer which produces normalized nodes
252 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
254 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
255 } catch (final IOException e) {
256 throw new IllegalStateException("Failed to serialize Binding DTO",e);
258 return result.getResult().data();
261 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
262 final NormalizedNode data) {
264 return expectedType.cast(requireNonNull(data));
265 } catch (ClassCastException e) {
266 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
270 // FIXME: MDSAL-780 replace this method with BindingRuntimeTypes-driven logic
271 static final Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
272 final String prefix) {
273 final String methodName = method.getName();
274 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
275 return Optional.empty();
278 final Class<?> returnType = method.getReturnType();
279 if (DataContainer.class.isAssignableFrom(returnType)) {
280 return optionalDataContainer(returnType);
281 } else if (List.class.isAssignableFrom(returnType)) {
282 return getYangModeledReturnType(method, 0);
283 } else if (Map.class.isAssignableFrom(returnType)) {
284 return getYangModeledReturnType(method, 1);
286 return Optional.empty();
289 @SuppressWarnings("checkstyle:illegalCatch")
290 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
291 final int parameterOffset) {
293 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(),
294 () -> genericParameter(method.getGenericReturnType(), parameterOffset)
295 .flatMap(result -> result instanceof Class ? optionalCast((Class<?>) result) : Optional.empty()));
296 } catch (Exception e) {
298 * It is safe to log this this exception on debug, since this
299 * method should not fail. Only failures are possible if the
302 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
304 return Optional.empty();
307 private static Optional<java.lang.reflect.Type> genericParameter(final java.lang.reflect.Type type,
309 if (type instanceof ParameterizedType parameterized) {
310 final var parameters = parameterized.getActualTypeArguments();
311 if (parameters.length > offset) {
312 return Optional.of(parameters[offset]);
315 return Optional.empty();
318 private static Optional<Class<? extends DataContainer>> optionalCast(final Class<?> type) {
319 return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty();
322 // FIXME: MDSAL-780: remove this method
323 static final Optional<Class<? extends DataContainer>> optionalDataContainer(final Class<?> type) {
324 return Optional.of(type.asSubclass(DataContainer.class));
328 * Determines if two augmentation classes or case classes represents same data.
331 * Two augmentations or cases could be substituted only if and if:
333 * <li>Both implements same interfaces</li>
334 * <li>Both have same children</li>
335 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
337 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
341 * <b>Explanation:</b>
342 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
343 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
344 * augmentation in particular subtree (via copy constructors, etc).
346 * @param potential Class which is potential substitution
347 * @param target Class which should be used at particular subtree
348 * @return true if and only if classes represents same data.
349 * @throws NullPointerException if any argument is {@code null}
351 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
352 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
353 // a particular world this boils down to a matrix, which can be calculated either on-demand or
354 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
355 // to have a pre-compiled Binding Runtime.
356 @SuppressWarnings({ "rawtypes", "unchecked" })
357 static final boolean isSubstitutionFor(final Class potential, final Class target) {
358 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
359 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
360 if (!subImplemented.equals(targetImplemented)) {
363 if (Augmentation.class.isAssignableFrom(potential)
364 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
367 for (Method potentialMethod : potential.getMethods()) {
368 if (Modifier.isStatic(potentialMethod.getModifiers())) {
369 // Skip any static methods, as we are not interested in those
374 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
375 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
378 } catch (NoSuchMethodException e) {
379 // Counterpart method is missing, so classes could not be substituted.
381 } catch (SecurityException e) {
382 throw new IllegalStateException("Could not compare methods", e);
389 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
390 * implemented {@link Augmentation} interface.
392 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
393 * @return Augmentation target - class which augmentation provides additional extensions.
395 static final Class<? extends Augmentable<?>> findAugmentationTarget(
396 final Class<? extends Augmentation<?>> augmentation) {
397 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
399 return opt.orElse(null);
404 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
405 // FIXME: rework this to work on EffectiveStatements
406 if (nodeSchema instanceof DataNodeContainer contaner) {
407 boolean haveAddressable = false;
408 boolean haveUnaddressable = false;
409 for (DataSchemaNode child : contaner.getChildNodes()) {
410 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
411 haveAddressable = true;
412 } else if (child instanceof ListSchemaNode list) {
413 if (list.getKeyDefinition().isEmpty()) {
414 haveUnaddressable = true;
416 haveAddressable = true;
418 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
419 || child instanceof TypedDataSchemaNode) {
420 haveUnaddressable = true;
421 } else if (child instanceof ChoiceSchemaNode choice) {
422 switch (computeChildAddressabilitySummary(choice)) {
423 case ADDRESSABLE -> haveAddressable = true;
424 case UNADDRESSABLE -> haveUnaddressable = true;
426 haveAddressable = true;
427 haveUnaddressable = true;
429 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
432 LOG.warn("Unhandled child node {}", child);
436 if (!haveAddressable) {
437 // Empty or all are unaddressable
438 return ChildAddressabilitySummary.UNADDRESSABLE;
441 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
442 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
443 return computeChildAddressabilitySummary(choice);
446 // No child nodes possible: return unaddressable
447 return ChildAddressabilitySummary.UNADDRESSABLE;
450 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
451 final ChoiceSchemaNode choice) {
452 boolean haveAddressable = false;
453 boolean haveUnaddressable = false;
454 for (CaseSchemaNode child : choice.getCases()) {
455 switch (computeChildAddressabilitySummary(child)) {
457 haveAddressable = true;
460 haveUnaddressable = true;
463 // A child is mixed, which means we are mixed, too
464 return ChildAddressabilitySummary.MIXED;
466 throw new IllegalStateException("Unhandled accessibility summary for " + child);
470 if (!haveAddressable) {
471 // Empty or all are unaddressable
472 return ChildAddressabilitySummary.UNADDRESSABLE;
475 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;