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.IncorrectNestingException;
31 import org.opendaylight.mdsal.binding.dom.codec.api.MissingClassInLoadingStrategyException;
32 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaException;
33 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaForClassException;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
36 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
37 import org.opendaylight.yangtools.util.ClassLoaderUtils;
38 import org.opendaylight.yangtools.yang.binding.Augmentable;
39 import org.opendaylight.yangtools.yang.binding.Augmentation;
40 import org.opendaylight.yangtools.yang.binding.BindingObject;
41 import org.opendaylight.yangtools.yang.binding.DataContainer;
42 import org.opendaylight.yangtools.yang.binding.DataObject;
43 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.common.QNameModule;
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 BindingObject & 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 private volatile DataContainerSerializer eventStreamSerializer;
86 DataContainerCodecContext(final T type) {
87 childAddressabilitySummary = computeChildAddressabilitySummary(type.statement());
91 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
92 return childAddressabilitySummary;
95 protected abstract @NonNull CodecContextFactory factory();
97 protected abstract @NonNull T type();
99 // Non-final for ChoiceCodecContext
101 public CodecContext yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
102 CodecContextSupplier supplier;
103 if (arg instanceof NodeIdentifier nodeId) {
104 supplier = yangChildSupplier(nodeId);
105 } else if (arg instanceof NodeIdentifierWithPredicates nip) {
106 supplier = yangChildSupplier(new NodeIdentifier(nip.getNodeType()));
110 return childNonNull(supplier, arg, "Argument %s is not valid child of %s", arg, getSchema()).get();
113 abstract @Nullable CodecContextSupplier yangChildSupplier(@NonNull NodeIdentifier arg);
116 public CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
117 final List<YangInstanceIdentifier.PathArgument> builder) {
118 final var child = getStreamChild(arg.getType());
119 child.addYangPathArgument(arg, builder);
124 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
126 * @param arg Binding Path Argument
127 * @param builder DOM Path argument.
129 final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
130 if (builder != null) {
131 addYangPathArgument(builder, arg);
135 void addYangPathArgument(final @NonNull List<YangInstanceIdentifier.PathArgument> builder, final PathArgument arg) {
136 final var yangArg = getDomPathArgument();
137 if (yangArg != null) {
138 builder.add(yangArg);
143 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(final Class<C> childClass) {
144 return childNonNull(streamChild(childClass), childClass,
145 "Child %s is not valid child of %s", getBindingClass(), childClass);
148 @SuppressWarnings("unchecked")
150 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(final Class<C> childClass) {
151 final var childProto = streamChildPrototype(requireNonNull(childClass));
152 return childProto == null ? null : (CommonDataObjectCodecContext<C, ?>) childProto.get();
155 abstract @Nullable CommonDataObjectCodecPrototype<?> streamChildPrototype(@NonNull Class<?> childClass);
158 public String toString() {
159 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
162 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?> & BindingNormalizedNodeCodec<T>>
163 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
164 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
165 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
166 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
169 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
170 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
171 if (nullable == null) {
172 throw childNullException(child.getNodeType(), message, args);
177 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
178 final Object... args) {
179 if (nullable == null) {
180 throw childNullException(child, message, args);
185 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
186 final String message, final Object... args) {
187 if (nullable == null) {
188 throw childNullException(childClass, message, args);
194 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
195 final QNameModule module = child.getModule();
196 if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
197 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
199 return new IncorrectNestingException(message, args);
203 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
204 final Object... args) {
205 return childNullException(factory().getRuntimeContext(), childClass, message, args);
209 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
210 final Class<?> childClass, final String message, final Object... args) {
211 final CompositeRuntimeType schema;
212 if (Augmentation.class.isAssignableFrom(childClass)) {
213 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
215 schema = runtimeContext.getSchemaDefinition(childClass);
217 if (schema == null) {
218 return new MissingSchemaForClassException(childClass);
222 runtimeContext.loadClass(Type.of(childClass));
223 } catch (final ClassNotFoundException e) {
224 return new MissingClassInLoadingStrategyException(
225 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
228 return new IncorrectNestingException(message, args);
231 final DataContainerSerializer eventStreamSerializer() {
232 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
233 return existing != null ? existing : loadEventStreamSerializer();
236 // Split out to aid inlining
237 private DataContainerSerializer loadEventStreamSerializer() {
238 final DataContainerSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
239 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
240 return witness == null ? loaded : (DataContainerSerializer) witness;
243 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
244 final var result = new NormalizationResultHolder();
245 // We create DOM stream writer which produces normalized nodes
246 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
248 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
249 } catch (final IOException e) {
250 throw new IllegalStateException("Failed to serialize Binding DTO",e);
252 return result.getResult().data();
255 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
256 final NormalizedNode data) {
258 return expectedType.cast(requireNonNull(data));
259 } catch (ClassCastException e) {
260 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
265 * Determines if two augmentation classes or case classes represents same data.
268 * Two augmentations or cases could be substituted only if and if:
270 * <li>Both implements same interfaces</li>
271 * <li>Both have same children</li>
272 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
274 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
278 * <b>Explanation:</b>
279 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
280 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
281 * augmentation in particular subtree (via copy constructors, etc).
283 * @param potential Class which is potential substitution
284 * @param target Class which should be used at particular subtree
285 * @return true if and only if classes represents same data.
286 * @throws NullPointerException if any argument is {@code null}
288 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
289 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
290 // a particular world this boils down to a matrix, which can be calculated either on-demand or
291 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
292 // to have a pre-compiled Binding Runtime.
293 @SuppressWarnings({ "rawtypes", "unchecked" })
294 static final boolean isSubstitutionFor(final Class potential, final Class target) {
295 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
296 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
297 if (!subImplemented.equals(targetImplemented)) {
300 if (Augmentation.class.isAssignableFrom(potential)
301 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
304 for (Method potentialMethod : potential.getMethods()) {
305 if (Modifier.isStatic(potentialMethod.getModifiers())) {
306 // Skip any static methods, as we are not interested in those
311 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
312 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
315 } catch (NoSuchMethodException e) {
316 // Counterpart method is missing, so classes could not be substituted.
318 } catch (SecurityException e) {
319 throw new IllegalStateException("Could not compare methods", e);
326 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
327 * implemented {@link Augmentation} interface.
329 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
330 * @return Augmentation target - class which augmentation provides additional extensions.
332 static final Class<? extends Augmentable<?>> findAugmentationTarget(
333 final Class<? extends Augmentation<?>> augmentation) {
334 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
336 return opt.orElse(null);
339 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
340 // FIXME: rework this to work on EffectiveStatements
341 if (nodeSchema instanceof DataNodeContainer contaner) {
342 boolean haveAddressable = false;
343 boolean haveUnaddressable = false;
344 for (DataSchemaNode child : contaner.getChildNodes()) {
345 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
346 haveAddressable = true;
347 } else if (child instanceof ListSchemaNode list) {
348 if (list.getKeyDefinition().isEmpty()) {
349 haveUnaddressable = true;
351 haveAddressable = true;
353 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
354 || child instanceof TypedDataSchemaNode) {
355 haveUnaddressable = true;
356 } else if (child instanceof ChoiceSchemaNode choice) {
357 switch (computeChildAddressabilitySummary(choice)) {
358 case ADDRESSABLE -> haveAddressable = true;
359 case UNADDRESSABLE -> haveUnaddressable = true;
361 haveAddressable = true;
362 haveUnaddressable = true;
364 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
367 LOG.warn("Unhandled child node {}", child);
371 if (!haveAddressable) {
372 // Empty or all are unaddressable
373 return ChildAddressabilitySummary.UNADDRESSABLE;
376 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
377 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
378 return computeChildAddressabilitySummary(choice);
381 // No child nodes possible: return unaddressable
382 return ChildAddressabilitySummary.UNADDRESSABLE;
385 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
386 final ChoiceSchemaNode choice) {
387 boolean haveAddressable = false;
388 boolean haveUnaddressable = false;
389 for (CaseSchemaNode child : choice.getCases()) {
390 switch (computeChildAddressabilitySummary(child)) {
392 haveAddressable = true;
395 haveUnaddressable = true;
398 // A child is mixed, which means we are mixed, too
399 return ChildAddressabilitySummary.MIXED;
401 throw new IllegalStateException("Unhandled accessibility summary for " + child);
405 if (!haveAddressable) {
406 // Empty or all are unaddressable
407 return ChildAddressabilitySummary.UNADDRESSABLE;
410 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;