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, T extends CompositeRuntimeType>
66 extends CodecContext implements BindingDataContainerCodecTreeNode<D>
67 permits CommonDataObjectCodecContext {
68 private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecContext.class);
69 private static final VarHandle EVENT_STREAM_SERIALIZER;
73 EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
74 "eventStreamSerializer", DataContainerSerializer.class);
75 } catch (NoSuchFieldException | IllegalAccessException e) {
76 throw new ExceptionInInitializerError(e);
80 private final @NonNull ChildAddressabilitySummary childAddressabilitySummary;
82 // Accessed via a VarHandle
83 @SuppressWarnings("unused")
84 @SuppressFBWarnings(value = "UUF_UNUSED_FIELD", justification = "https://github.com/spotbugs/spotbugs/issues/2749")
85 private volatile DataContainerSerializer eventStreamSerializer;
87 DataContainerCodecContext(final T type) {
88 childAddressabilitySummary = computeChildAddressabilitySummary(type.statement());
92 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
93 return childAddressabilitySummary;
96 protected abstract @NonNull CodecContextFactory factory();
98 protected abstract @NonNull T type();
100 // Non-final for ChoiceCodecContext
102 public CodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
103 CodecContextSupplier supplier;
104 if (arg instanceof NodeIdentifier nodeId) {
105 supplier = yangChildSupplier(nodeId);
106 } else if (arg instanceof NodeIdentifierWithPredicates nip) {
107 supplier = yangChildSupplier(new NodeIdentifier(nip.getNodeType()));
111 return childNonNull(supplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).getCodecContext();
114 abstract @Nullable CodecContextSupplier yangChildSupplier(@NonNull NodeIdentifier arg);
117 public CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
118 final List<YangInstanceIdentifier.PathArgument> builder) {
119 final var child = getStreamChild(arg.getType());
120 child.addYangPathArgument(arg, builder);
125 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
127 * @param arg Binding Path Argument
128 * @param builder DOM Path argument.
130 final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
131 if (builder != null) {
132 addYangPathArgument(builder, arg);
136 void addYangPathArgument(final @NonNull List<YangInstanceIdentifier.PathArgument> builder, final PathArgument arg) {
137 final var yangArg = getDomPathArgument();
138 if (yangArg != null) {
139 builder.add(yangArg);
144 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(final Class<C> childClass) {
145 return childNonNull(streamChild(childClass), childClass,
146 "Child %s is not valid child of %s", getBindingClass(), childClass);
149 @SuppressWarnings("unchecked")
151 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(final Class<C> childClass) {
152 final var childProto = streamChildPrototype(requireNonNull(childClass));
153 return childProto == null ? null : (CommonDataObjectCodecContext<C, ?>) childProto.getCodecContext();
156 abstract @Nullable CommonDataObjectCodecPrototype<?> streamChildPrototype(@NonNull Class<?> childClass);
159 public String toString() {
160 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
163 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?> & BindingNormalizedNodeCodec<T>>
164 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
165 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
166 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
167 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
170 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
171 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
172 if (nullable == null) {
173 throw childNullException(child.getNodeType(), message, args);
178 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
179 final Object... args) {
180 if (nullable == null) {
181 throw childNullException(child, message, args);
186 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
187 final String message, final Object... args) {
188 if (nullable == null) {
189 throw childNullException(childClass, message, args);
195 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
196 final var module = child.getModule();
197 if (!factory().getRuntimeContext().modelContext().findModule(module).isPresent()) {
198 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
200 return new IncorrectNestingException(message, args);
204 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
205 final Object... args) {
206 return childNullException(factory().getRuntimeContext(), childClass, message, args);
210 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
211 final Class<?> childClass, final String message, final Object... args) {
212 final CompositeRuntimeType schema;
213 if (Augmentation.class.isAssignableFrom(childClass)) {
214 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
216 schema = runtimeContext.getSchemaDefinition(childClass);
218 if (schema == null) {
219 return new MissingSchemaForClassException(childClass);
223 runtimeContext.loadClass(Type.of(childClass));
224 } catch (final ClassNotFoundException e) {
225 return new MissingClassInLoadingStrategyException(
226 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
229 return new IncorrectNestingException(message, args);
232 final DataContainerSerializer eventStreamSerializer() {
233 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
234 return existing != null ? existing : loadEventStreamSerializer();
237 // Split out to aid inlining
238 private DataContainerSerializer loadEventStreamSerializer() {
239 final DataContainerSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
240 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
241 return witness == null ? loaded : (DataContainerSerializer) witness;
244 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
245 final var result = new NormalizationResultHolder();
246 // We create DOM stream writer which produces normalized nodes
247 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
249 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
250 } catch (final IOException e) {
251 throw new IllegalStateException("Failed to serialize Binding DTO",e);
253 return result.getResult().data();
256 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
257 final NormalizedNode data) {
259 return expectedType.cast(requireNonNull(data));
260 } catch (ClassCastException e) {
261 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
266 * Determines if two augmentation classes or case classes represents same data.
269 * Two augmentations or cases could be substituted only if and if:
271 * <li>Both implements same interfaces</li>
272 * <li>Both have same children</li>
273 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
275 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
279 * <b>Explanation:</b>
280 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
281 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
282 * augmentation in particular subtree (via copy constructors, etc).
284 * @param potential Class which is potential substitution
285 * @param target Class which should be used at particular subtree
286 * @return true if and only if classes represents same data.
287 * @throws NullPointerException if any argument is {@code null}
289 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
290 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
291 // a particular world this boils down to a matrix, which can be calculated either on-demand or
292 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
293 // to have a pre-compiled Binding Runtime.
294 @SuppressWarnings({ "rawtypes", "unchecked" })
295 static final boolean isSubstitutionFor(final Class potential, final Class target) {
296 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
297 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
298 if (!subImplemented.equals(targetImplemented)) {
301 if (Augmentation.class.isAssignableFrom(potential)
302 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
305 for (Method potentialMethod : potential.getMethods()) {
306 if (Modifier.isStatic(potentialMethod.getModifiers())) {
307 // Skip any static methods, as we are not interested in those
312 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
313 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
316 } catch (NoSuchMethodException e) {
317 // Counterpart method is missing, so classes could not be substituted.
319 } catch (SecurityException e) {
320 throw new IllegalStateException("Could not compare methods", e);
327 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
328 * implemented {@link Augmentation} interface.
330 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
331 * @return Augmentation target - class which augmentation provides additional extensions.
333 static final Class<? extends Augmentable<?>> findAugmentationTarget(
334 final Class<? extends Augmentation<?>> augmentation) {
335 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
337 return opt.orElse(null);
340 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
341 // FIXME: rework this to work on EffectiveStatements
342 if (nodeSchema instanceof DataNodeContainer contaner) {
343 boolean haveAddressable = false;
344 boolean haveUnaddressable = false;
345 for (DataSchemaNode child : contaner.getChildNodes()) {
346 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
347 haveAddressable = true;
348 } else if (child instanceof ListSchemaNode list) {
349 if (list.getKeyDefinition().isEmpty()) {
350 haveUnaddressable = true;
352 haveAddressable = true;
354 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
355 || child instanceof TypedDataSchemaNode) {
356 haveUnaddressable = true;
357 } else if (child instanceof ChoiceSchemaNode choice) {
358 switch (computeChildAddressabilitySummary(choice)) {
359 case ADDRESSABLE -> haveAddressable = true;
360 case UNADDRESSABLE -> haveUnaddressable = true;
362 haveAddressable = true;
363 haveUnaddressable = true;
365 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
368 LOG.warn("Unhandled child node {}", child);
372 if (!haveAddressable) {
373 // Empty or all are unaddressable
374 return ChildAddressabilitySummary.UNADDRESSABLE;
377 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
378 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
379 return computeChildAddressabilitySummary(choice);
382 // No child nodes possible: return unaddressable
383 return ChildAddressabilitySummary.UNADDRESSABLE;
386 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
387 final ChoiceSchemaNode choice) {
388 boolean haveAddressable = false;
389 boolean haveUnaddressable = false;
390 for (CaseSchemaNode child : choice.getCases()) {
391 switch (computeChildAddressabilitySummary(child)) {
393 haveAddressable = true;
396 haveUnaddressable = true;
399 // A child is mixed, which means we are mixed, too
400 return ChildAddressabilitySummary.MIXED;
402 throw new IllegalStateException("Unhandled accessibility summary for " + child);
406 if (!haveAddressable) {
407 // Empty or all are unaddressable
408 return ChildAddressabilitySummary.UNADDRESSABLE;
411 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;