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 edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
16 import java.io.IOException;
17 import java.lang.invoke.MethodHandles;
18 import java.lang.invoke.VarHandle;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Modifier;
21 import java.util.Arrays;
22 import java.util.HashSet;
23 import java.util.List;
24 import java.util.Optional;
26 import org.eclipse.jdt.annotation.NonNull;
27 import org.eclipse.jdt.annotation.Nullable;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataContainerCodecTreeNode;
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.IncorrectNestingException;
32 import org.opendaylight.mdsal.binding.dom.codec.api.MissingClassInLoadingStrategyException;
33 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaException;
34 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaForClassException;
35 import org.opendaylight.mdsal.binding.model.api.Type;
36 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
37 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
38 import org.opendaylight.yangtools.util.ClassLoaderUtils;
39 import org.opendaylight.yangtools.yang.binding.Augmentable;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.binding.BindingObject;
42 import org.opendaylight.yangtools.yang.binding.DataContainer;
43 import org.opendaylight.yangtools.yang.binding.DataObject;
44 import org.opendaylight.yangtools.yang.binding.DataObjectStep;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
50 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
51 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
52 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
65 abstract sealed class DataContainerCodecContext<D extends DataContainer, R extends CompositeRuntimeType,
66 P extends DataContainerPrototype<?, R>>
67 extends CodecContext implements BindingDataContainerCodecTreeNode<D>
68 permits ChoiceCodecContext, CommonDataObjectCodecContext {
69 private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecContext.class);
70 private static final VarHandle EVENT_STREAM_SERIALIZER;
74 EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
75 "eventStreamSerializer", DataContainerSerializer.class);
76 } catch (NoSuchFieldException | IllegalAccessException e) {
77 throw new ExceptionInInitializerError(e);
81 private final @NonNull P prototype;
82 private final @NonNull ChildAddressabilitySummary childAddressabilitySummary;
84 // Accessed via a VarHandle
85 @SuppressWarnings("unused")
86 @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
87 private volatile DataContainerSerializer eventStreamSerializer;
89 DataContainerCodecContext(final P prototype) {
90 this.prototype = requireNonNull(prototype);
91 childAddressabilitySummary = computeChildAddressabilitySummary(prototype.runtimeType().statement());
94 final @NonNull P prototype() {
99 @SuppressWarnings("unchecked")
100 public final Class<D> getBindingClass() {
101 return (Class<D>) prototype().javaClass();
104 // overridden in AugmentationCodecContext
106 NodeIdentifier getDomPathArgument() {
107 return prototype.yangArg();
111 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
112 return childAddressabilitySummary;
115 // Non-final for ChoiceCodecContext
117 public CodecContext yangPathArgumentChild(final PathArgument arg) {
118 CodecContextSupplier supplier;
119 if (arg instanceof NodeIdentifier nodeId) {
120 supplier = yangChildSupplier(nodeId);
121 } else if (arg instanceof NodeIdentifierWithPredicates nip) {
122 supplier = yangChildSupplier(new NodeIdentifier(nip.getNodeType()));
126 return childNonNull(supplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).getCodecContext();
129 abstract @Nullable CodecContextSupplier yangChildSupplier(@NonNull NodeIdentifier arg);
132 public abstract CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(DataObjectStep<?> step,
133 List<PathArgument> builder);
136 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
138 * @param step Binding Path Argument
139 * @param builder DOM Path argument.
141 final void addYangPathArgument(final DataObjectStep<?> step, final List<PathArgument> builder) {
142 if (builder != null) {
143 addYangPathArgument(builder, step);
147 void addYangPathArgument(final @NonNull List<PathArgument> builder, final DataObjectStep<?> step) {
148 final var yangArg = getDomPathArgument();
149 if (yangArg != null) {
150 builder.add(yangArg);
155 public final <C extends DataObject> DataContainerCodecContext<C, ?, ?> getStreamChild(final Class<C> childClass) {
156 return childNonNull(streamChild(childClass), childClass,
157 "Child %s is not valid child of %s", getBindingClass(), childClass);
160 @SuppressWarnings("unchecked")
162 public final <C extends DataObject> DataContainerCodecContext<C, ?, ?> streamChild(final Class<C> childClass) {
163 final var childProto = streamChildPrototype(requireNonNull(childClass));
164 return childProto == null ? null : (DataContainerCodecContext<C, ?, ?>) childProto.getCodecContext();
167 abstract @Nullable DataContainerPrototype<?, ?> streamChildPrototype(@NonNull Class<?> childClass);
170 public String toString() {
171 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
174 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?, ?> & BindingNormalizedNodeCodec<T>>
175 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
176 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
177 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
178 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
181 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final PathArgument child,
182 final String message, final Object... args) {
183 if (nullable == null) {
184 throw childNullException(child.getNodeType(), message, args);
189 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
190 final Object... args) {
191 if (nullable == null) {
192 throw childNullException(child, message, args);
197 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
198 final String message, final Object... args) {
199 if (nullable == null) {
200 throw childNullException(childClass, message, args);
206 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
207 final var module = child.getModule();
208 if (!prototype().contextFactory().getRuntimeContext().modelContext().findModule(module).isPresent()) {
209 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
211 return new IncorrectNestingException(message, args);
215 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
216 final Object... args) {
217 return childNullException(prototype().contextFactory().getRuntimeContext(), childClass, message, args);
221 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
222 final Class<?> childClass, final String message, final Object... args) {
223 final CompositeRuntimeType schema;
224 if (Augmentation.class.isAssignableFrom(childClass)) {
225 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
227 schema = runtimeContext.getSchemaDefinition(childClass);
229 if (schema == null) {
230 return new MissingSchemaForClassException(childClass);
234 runtimeContext.loadClass(Type.of(childClass));
235 } catch (final ClassNotFoundException e) {
236 return new MissingClassInLoadingStrategyException(
237 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
240 return new IncorrectNestingException(message, args);
243 final DataContainerSerializer eventStreamSerializer() {
244 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
245 return existing != null ? existing : loadEventStreamSerializer();
248 // Split out to aid inlining
249 private DataContainerSerializer loadEventStreamSerializer() {
250 final DataContainerSerializer loaded = prototype().contextFactory().getEventStreamSerializer(getBindingClass());
251 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
252 return witness == null ? loaded : (DataContainerSerializer) witness;
255 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
256 final var result = new NormalizationResultHolder();
257 // We create DOM stream writer which produces normalized nodes
258 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
260 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
261 } catch (final IOException e) {
262 throw new IllegalStateException("Failed to serialize Binding DTO",e);
264 return result.getResult().data();
267 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
268 final NormalizedNode data) {
270 return expectedType.cast(requireNonNull(data));
271 } catch (ClassCastException e) {
272 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
277 * Determines if two augmentation classes or case classes represents same data.
280 * Two augmentations or cases could be substituted only if and if:
282 * <li>Both implements same interfaces</li>
283 * <li>Both have same children</li>
284 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
286 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
290 * <b>Explanation:</b>
291 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
292 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
293 * augmentation in particular subtree (via copy constructors, etc).
295 * @param potential Class which is potential substitution
296 * @param target Class which should be used at particular subtree
297 * @return true if and only if classes represents same data.
298 * @throws NullPointerException if any argument is {@code null}
300 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
301 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
302 // a particular world this boils down to a matrix, which can be calculated either on-demand or
303 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
304 // to have a pre-compiled Binding Runtime.
305 @SuppressWarnings({ "rawtypes", "unchecked" })
306 static final boolean isSubstitutionFor(final Class potential, final Class target) {
307 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
308 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
309 if (!subImplemented.equals(targetImplemented)) {
312 if (Augmentation.class.isAssignableFrom(potential)
313 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
316 for (Method potentialMethod : potential.getMethods()) {
317 if (Modifier.isStatic(potentialMethod.getModifiers())) {
318 // Skip any static methods, as we are not interested in those
323 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
324 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
327 } catch (NoSuchMethodException e) {
328 // Counterpart method is missing, so classes could not be substituted.
330 } catch (SecurityException e) {
331 throw new IllegalStateException("Could not compare methods", e);
338 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
339 * implemented {@link Augmentation} interface.
341 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
342 * @return Augmentation target - class which augmentation provides additional extensions.
344 static final Class<? extends Augmentable<?>> findAugmentationTarget(
345 final Class<? extends Augmentation<?>> augmentation) {
346 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
348 return opt.orElse(null);
351 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
352 // FIXME: rework this to work on EffectiveStatements
353 if (nodeSchema instanceof DataNodeContainer contaner) {
354 boolean haveAddressable = false;
355 boolean haveUnaddressable = false;
356 for (DataSchemaNode child : contaner.getChildNodes()) {
357 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
358 haveAddressable = true;
359 } else if (child instanceof ListSchemaNode list) {
360 if (list.getKeyDefinition().isEmpty()) {
361 haveUnaddressable = true;
363 haveAddressable = true;
365 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
366 || child instanceof TypedDataSchemaNode) {
367 haveUnaddressable = true;
368 } else if (child instanceof ChoiceSchemaNode choice) {
369 switch (computeChildAddressabilitySummary(choice)) {
370 case ADDRESSABLE -> haveAddressable = true;
371 case UNADDRESSABLE -> haveUnaddressable = true;
373 haveAddressable = true;
374 haveUnaddressable = true;
376 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
379 LOG.warn("Unhandled child node {}", child);
383 if (!haveAddressable) {
384 // Empty or all are unaddressable
385 return ChildAddressabilitySummary.UNADDRESSABLE;
388 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
389 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
390 return computeChildAddressabilitySummary(choice);
393 // No child nodes possible: return unaddressable
394 return ChildAddressabilitySummary.UNADDRESSABLE;
397 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
398 final ChoiceSchemaNode choice) {
399 boolean haveAddressable = false;
400 boolean haveUnaddressable = false;
401 for (CaseSchemaNode child : choice.getCases()) {
402 switch (computeChildAddressabilitySummary(child)) {
404 haveAddressable = true;
407 haveUnaddressable = true;
410 // A child is mixed, which means we are mixed, too
411 return ChildAddressabilitySummary.MIXED;
413 throw new IllegalStateException("Unhandled accessibility summary for " + child);
417 if (!haveAddressable) {
418 // Empty or all are unaddressable
419 return ChildAddressabilitySummary.UNADDRESSABLE;
422 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;