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.util.Arrays;
21 import java.util.HashSet;
22 import java.util.List;
23 import java.util.Optional;
25 import org.eclipse.jdt.annotation.NonNull;
26 import org.eclipse.jdt.annotation.Nullable;
27 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataContainerCodecTreeNode;
28 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCodec;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingStreamEventWriter;
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.mdsal.binding.runtime.api.RuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.RuntimeTypeContainer;
40 import org.opendaylight.yangtools.util.ClassLoaderUtils;
41 import org.opendaylight.yangtools.yang.binding.Augmentable;
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.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
52 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
53 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
60 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
61 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
63 import org.slf4j.Logger;
64 import org.slf4j.LoggerFactory;
66 abstract sealed class DataContainerCodecContext<D extends BindingObject & DataContainer, T extends RuntimeTypeContainer>
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 ChildAddressabilitySummary childAddressabilitySummary;
83 // Accessed via a VarHandle
84 @SuppressWarnings("unused")
85 private volatile DataContainerSerializer eventStreamSerializer;
87 DataContainerCodecContext(final T type) {
88 childAddressabilitySummary = type instanceof RuntimeType runtimeType
89 ? computeChildAddressabilitySummary(runtimeType.statement())
90 // BindingRuntimeTypes, does not matter
91 : ChildAddressabilitySummary.MIXED;
95 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
96 return childAddressabilitySummary;
99 protected abstract @NonNull CodecContextFactory factory();
101 protected abstract @NonNull T type();
104 * Returns nested node context using supplied YANG Instance Identifier.
106 * @param arg Yang Instance Identifier Argument
107 * @return Context of child
108 * @throws IllegalArgumentException If supplied argument does not represent valid child.
111 public abstract CodecContext yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg);
114 * Returns nested node context using supplied Binding Instance Identifier
115 * and adds YANG instance identifiers to supplied list.
117 * @param arg Binding Instance Identifier Argument
118 * @return Context of child or null if supplied {@code arg} does not represent valid child.
119 * @throws IllegalArgumentException If supplied argument does not represent valid child.
122 public CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
123 final List<YangInstanceIdentifier.PathArgument> builder) {
124 final var child = getStreamChild(arg.getType());
125 child.addYangPathArgument(arg, builder);
130 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
132 * @param arg Binding Path Argument
133 * @param builder DOM Path argument.
135 final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
136 if (builder != null) {
137 addYangPathArgument(builder, arg);
141 void addYangPathArgument(final @NonNull List<YangInstanceIdentifier.PathArgument> builder, final PathArgument arg) {
142 final var yangArg = getDomPathArgument();
143 if (yangArg != null) {
144 builder.add(yangArg);
149 public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(Class<C> childClass);
152 * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
153 * must issue getChild(ChoiceClass).getChild(CaseClass).
155 * @param childClass child class
156 * @return Context of child or Optional.empty is supplied class is not applicable in context.
159 public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(Class<C> 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 QNameModule module = child.getModule();
200 if (!factory().getRuntimeContext().getEffectiveModelContext().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(factory().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 = factory().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);
345 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
346 // FIXME: rework this to work on EffectiveStatements
347 if (nodeSchema instanceof DataNodeContainer contaner) {
348 boolean haveAddressable = false;
349 boolean haveUnaddressable = false;
350 for (DataSchemaNode child : contaner.getChildNodes()) {
351 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
352 haveAddressable = true;
353 } else if (child instanceof ListSchemaNode list) {
354 if (list.getKeyDefinition().isEmpty()) {
355 haveUnaddressable = true;
357 haveAddressable = true;
359 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
360 || child instanceof TypedDataSchemaNode) {
361 haveUnaddressable = true;
362 } else if (child instanceof ChoiceSchemaNode choice) {
363 switch (computeChildAddressabilitySummary(choice)) {
364 case ADDRESSABLE -> haveAddressable = true;
365 case UNADDRESSABLE -> haveUnaddressable = true;
367 haveAddressable = true;
368 haveUnaddressable = true;
370 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
373 LOG.warn("Unhandled child node {}", child);
377 if (!haveAddressable) {
378 // Empty or all are unaddressable
379 return ChildAddressabilitySummary.UNADDRESSABLE;
382 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
383 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
384 return computeChildAddressabilitySummary(choice);
387 // No child nodes possible: return unaddressable
388 return ChildAddressabilitySummary.UNADDRESSABLE;
391 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
392 final ChoiceSchemaNode choice) {
393 boolean haveAddressable = false;
394 boolean haveUnaddressable = false;
395 for (CaseSchemaNode child : choice.getCases()) {
396 switch (computeChildAddressabilitySummary(child)) {
398 haveAddressable = true;
401 haveUnaddressable = true;
404 // A child is mixed, which means we are mixed, too
405 return ChildAddressabilitySummary.MIXED;
407 throw new IllegalStateException("Unhandled accessibility summary for " + child);
411 if (!haveAddressable) {
412 // Empty or all are unaddressable
413 return ChildAddressabilitySummary.UNADDRESSABLE;
416 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;