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.InstanceIdentifier.PathArgument;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
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 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 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
100 return childAddressabilitySummary;
103 // Non-final for ChoiceCodecContext
105 public CodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
106 CodecContextSupplier supplier;
107 if (arg instanceof NodeIdentifier nodeId) {
108 supplier = yangChildSupplier(nodeId);
109 } else if (arg instanceof NodeIdentifierWithPredicates nip) {
110 supplier = yangChildSupplier(new NodeIdentifier(nip.getNodeType()));
114 return childNonNull(supplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).getCodecContext();
117 abstract @Nullable CodecContextSupplier yangChildSupplier(@NonNull NodeIdentifier arg);
120 public CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
121 final List<YangInstanceIdentifier.PathArgument> builder) {
122 final var child = getStreamChild(arg.getType());
123 child.addYangPathArgument(arg, builder);
128 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
130 * @param arg Binding Path Argument
131 * @param builder DOM Path argument.
133 final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
134 if (builder != null) {
135 addYangPathArgument(builder, arg);
139 void addYangPathArgument(final @NonNull List<YangInstanceIdentifier.PathArgument> builder, final PathArgument arg) {
140 final var yangArg = getDomPathArgument();
141 if (yangArg != null) {
142 builder.add(yangArg);
147 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(final Class<C> childClass) {
148 return childNonNull(streamChild(childClass), childClass,
149 "Child %s is not valid child of %s", getBindingClass(), childClass);
152 @SuppressWarnings("unchecked")
154 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(final Class<C> childClass) {
155 final var childProto = streamChildPrototype(requireNonNull(childClass));
156 return childProto == null ? null : (CommonDataObjectCodecContext<C, ?>) childProto.getCodecContext();
159 abstract @Nullable CommonDataObjectCodecPrototype<?> streamChildPrototype(@NonNull Class<?> childClass);
162 public String toString() {
163 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
166 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?, ?> & BindingNormalizedNodeCodec<T>>
167 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
168 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
169 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
170 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
173 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
174 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
175 if (nullable == null) {
176 throw childNullException(child.getNodeType(), message, args);
181 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
182 final Object... args) {
183 if (nullable == null) {
184 throw childNullException(child, message, args);
189 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
190 final String message, final Object... args) {
191 if (nullable == null) {
192 throw childNullException(childClass, message, args);
198 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
199 final var module = child.getModule();
200 if (!prototype().contextFactory().getRuntimeContext().modelContext().findModule(module).isPresent()) {
201 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
203 return new IncorrectNestingException(message, args);
207 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
208 final Object... args) {
209 return childNullException(prototype().contextFactory().getRuntimeContext(), childClass, message, args);
213 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
214 final Class<?> childClass, final String message, final Object... args) {
215 final CompositeRuntimeType schema;
216 if (Augmentation.class.isAssignableFrom(childClass)) {
217 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
219 schema = runtimeContext.getSchemaDefinition(childClass);
221 if (schema == null) {
222 return new MissingSchemaForClassException(childClass);
226 runtimeContext.loadClass(Type.of(childClass));
227 } catch (final ClassNotFoundException e) {
228 return new MissingClassInLoadingStrategyException(
229 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
232 return new IncorrectNestingException(message, args);
235 final DataContainerSerializer eventStreamSerializer() {
236 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
237 return existing != null ? existing : loadEventStreamSerializer();
240 // Split out to aid inlining
241 private DataContainerSerializer loadEventStreamSerializer() {
242 final DataContainerSerializer loaded = prototype().contextFactory().getEventStreamSerializer(getBindingClass());
243 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
244 return witness == null ? loaded : (DataContainerSerializer) witness;
247 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
248 final var result = new NormalizationResultHolder();
249 // We create DOM stream writer which produces normalized nodes
250 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
252 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
253 } catch (final IOException e) {
254 throw new IllegalStateException("Failed to serialize Binding DTO",e);
256 return result.getResult().data();
259 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
260 final NormalizedNode data) {
262 return expectedType.cast(requireNonNull(data));
263 } catch (ClassCastException e) {
264 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
269 * Determines if two augmentation classes or case classes represents same data.
272 * Two augmentations or cases could be substituted only if and if:
274 * <li>Both implements same interfaces</li>
275 * <li>Both have same children</li>
276 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
278 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
282 * <b>Explanation:</b>
283 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
284 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
285 * augmentation in particular subtree (via copy constructors, etc).
287 * @param potential Class which is potential substitution
288 * @param target Class which should be used at particular subtree
289 * @return true if and only if classes represents same data.
290 * @throws NullPointerException if any argument is {@code null}
292 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
293 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
294 // a particular world this boils down to a matrix, which can be calculated either on-demand or
295 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
296 // to have a pre-compiled Binding Runtime.
297 @SuppressWarnings({ "rawtypes", "unchecked" })
298 static final boolean isSubstitutionFor(final Class potential, final Class target) {
299 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
300 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
301 if (!subImplemented.equals(targetImplemented)) {
304 if (Augmentation.class.isAssignableFrom(potential)
305 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
308 for (Method potentialMethod : potential.getMethods()) {
309 if (Modifier.isStatic(potentialMethod.getModifiers())) {
310 // Skip any static methods, as we are not interested in those
315 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
316 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
319 } catch (NoSuchMethodException e) {
320 // Counterpart method is missing, so classes could not be substituted.
322 } catch (SecurityException e) {
323 throw new IllegalStateException("Could not compare methods", e);
330 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
331 * implemented {@link Augmentation} interface.
333 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
334 * @return Augmentation target - class which augmentation provides additional extensions.
336 static final Class<? extends Augmentable<?>> findAugmentationTarget(
337 final Class<? extends Augmentation<?>> augmentation) {
338 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
340 return opt.orElse(null);
343 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
344 // FIXME: rework this to work on EffectiveStatements
345 if (nodeSchema instanceof DataNodeContainer contaner) {
346 boolean haveAddressable = false;
347 boolean haveUnaddressable = false;
348 for (DataSchemaNode child : contaner.getChildNodes()) {
349 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
350 haveAddressable = true;
351 } else if (child instanceof ListSchemaNode list) {
352 if (list.getKeyDefinition().isEmpty()) {
353 haveUnaddressable = true;
355 haveAddressable = true;
357 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
358 || child instanceof TypedDataSchemaNode) {
359 haveUnaddressable = true;
360 } else if (child instanceof ChoiceSchemaNode choice) {
361 switch (computeChildAddressabilitySummary(choice)) {
362 case ADDRESSABLE -> haveAddressable = true;
363 case UNADDRESSABLE -> haveUnaddressable = true;
365 haveAddressable = true;
366 haveUnaddressable = true;
368 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
371 LOG.warn("Unhandled child node {}", child);
375 if (!haveAddressable) {
376 // Empty or all are unaddressable
377 return ChildAddressabilitySummary.UNADDRESSABLE;
380 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
381 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
382 return computeChildAddressabilitySummary(choice);
385 // No child nodes possible: return unaddressable
386 return ChildAddressabilitySummary.UNADDRESSABLE;
389 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
390 final ChoiceSchemaNode choice) {
391 boolean haveAddressable = false;
392 boolean haveUnaddressable = false;
393 for (CaseSchemaNode child : choice.getCases()) {
394 switch (computeChildAddressabilitySummary(child)) {
396 haveAddressable = true;
399 haveUnaddressable = true;
402 // A child is mixed, which means we are mixed, too
403 return ChildAddressabilitySummary.MIXED;
405 throw new IllegalStateException("Unhandled accessibility summary for " + child);
409 if (!haveAddressable) {
410 // Empty or all are unaddressable
411 return ChildAddressabilitySummary.UNADDRESSABLE;
414 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;