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.schema.NormalizedNode;
48 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
49 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizationResultHolder;
50 import org.opendaylight.yangtools.yang.model.api.AnydataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.AnyxmlSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.ContainerSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
57 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 abstract sealed class DataContainerCodecContext<D extends BindingObject & DataContainer, T extends CompositeRuntimeType>
64 extends CodecContext implements BindingDataContainerCodecTreeNode<D>
65 permits CommonDataObjectCodecContext {
66 private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecContext.class);
67 private static final VarHandle EVENT_STREAM_SERIALIZER;
71 EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
72 "eventStreamSerializer", DataContainerSerializer.class);
73 } catch (NoSuchFieldException | IllegalAccessException e) {
74 throw new ExceptionInInitializerError(e);
78 private final @NonNull ChildAddressabilitySummary childAddressabilitySummary;
80 // Accessed via a VarHandle
81 @SuppressWarnings("unused")
82 private volatile DataContainerSerializer eventStreamSerializer;
84 DataContainerCodecContext(final T type) {
85 childAddressabilitySummary = computeChildAddressabilitySummary(type.statement());
89 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
90 return childAddressabilitySummary;
93 protected abstract @NonNull CodecContextFactory factory();
95 protected abstract @NonNull T type();
98 public abstract CodecContext yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg);
101 public CommonDataObjectCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
102 final List<YangInstanceIdentifier.PathArgument> builder) {
103 final var child = getStreamChild(arg.getType());
104 child.addYangPathArgument(arg, builder);
109 * Serializes supplied Binding Path Argument and adds all necessary YANG instance identifiers to supplied list.
111 * @param arg Binding Path Argument
112 * @param builder DOM Path argument.
114 final void addYangPathArgument(final PathArgument arg, final List<YangInstanceIdentifier.PathArgument> builder) {
115 if (builder != null) {
116 addYangPathArgument(builder, arg);
120 void addYangPathArgument(final @NonNull List<YangInstanceIdentifier.PathArgument> builder, final PathArgument arg) {
121 final var yangArg = getDomPathArgument();
122 if (yangArg != null) {
123 builder.add(yangArg);
128 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> getStreamChild(final Class<C> childClass) {
129 return childNonNull(streamChild(childClass), childClass,
130 "Child %s is not valid child of %s", getBindingClass(), childClass);
133 @SuppressWarnings("unchecked")
135 public final <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(final Class<C> childClass) {
136 final var childProto = streamChildPrototype(requireNonNull(childClass));
137 return childProto == null ? null : (CommonDataObjectCodecContext<C, ?>) childProto.get();
140 abstract @Nullable CommonDataObjectCodecPrototype<?> streamChildPrototype(@NonNull Class<?> childClass);
143 public String toString() {
144 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
147 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?> & BindingNormalizedNodeCodec<T>>
148 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
149 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
150 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
151 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
154 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
155 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
156 if (nullable == null) {
157 throw childNullException(child.getNodeType(), message, args);
162 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
163 final Object... args) {
164 if (nullable == null) {
165 throw childNullException(child, message, args);
170 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
171 final String message, final Object... args) {
172 if (nullable == null) {
173 throw childNullException(childClass, message, args);
179 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
180 final QNameModule module = child.getModule();
181 if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
182 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
184 return new IncorrectNestingException(message, args);
188 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
189 final Object... args) {
190 return childNullException(factory().getRuntimeContext(), childClass, message, args);
194 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
195 final Class<?> childClass, final String message, final Object... args) {
196 final CompositeRuntimeType schema;
197 if (Augmentation.class.isAssignableFrom(childClass)) {
198 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
200 schema = runtimeContext.getSchemaDefinition(childClass);
202 if (schema == null) {
203 return new MissingSchemaForClassException(childClass);
207 runtimeContext.loadClass(Type.of(childClass));
208 } catch (final ClassNotFoundException e) {
209 return new MissingClassInLoadingStrategyException(
210 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
213 return new IncorrectNestingException(message, args);
216 final DataContainerSerializer eventStreamSerializer() {
217 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
218 return existing != null ? existing : loadEventStreamSerializer();
221 // Split out to aid inlining
222 private DataContainerSerializer loadEventStreamSerializer() {
223 final DataContainerSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
224 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
225 return witness == null ? loaded : (DataContainerSerializer) witness;
228 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
229 final var result = new NormalizationResultHolder();
230 // We create DOM stream writer which produces normalized nodes
231 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
233 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
234 } catch (final IOException e) {
235 throw new IllegalStateException("Failed to serialize Binding DTO",e);
237 return result.getResult().data();
240 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
241 final NormalizedNode data) {
243 return expectedType.cast(requireNonNull(data));
244 } catch (ClassCastException e) {
245 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
250 * Determines if two augmentation classes or case classes represents same data.
253 * Two augmentations or cases could be substituted only if and if:
255 * <li>Both implements same interfaces</li>
256 * <li>Both have same children</li>
257 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
259 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
263 * <b>Explanation:</b>
264 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
265 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
266 * augmentation in particular subtree (via copy constructors, etc).
268 * @param potential Class which is potential substitution
269 * @param target Class which should be used at particular subtree
270 * @return true if and only if classes represents same data.
271 * @throws NullPointerException if any argument is {@code null}
273 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
274 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
275 // a particular world this boils down to a matrix, which can be calculated either on-demand or
276 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
277 // to have a pre-compiled Binding Runtime.
278 @SuppressWarnings({ "rawtypes", "unchecked" })
279 static final boolean isSubstitutionFor(final Class potential, final Class target) {
280 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
281 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
282 if (!subImplemented.equals(targetImplemented)) {
285 if (Augmentation.class.isAssignableFrom(potential)
286 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
289 for (Method potentialMethod : potential.getMethods()) {
290 if (Modifier.isStatic(potentialMethod.getModifiers())) {
291 // Skip any static methods, as we are not interested in those
296 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
297 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
300 } catch (NoSuchMethodException e) {
301 // Counterpart method is missing, so classes could not be substituted.
303 } catch (SecurityException e) {
304 throw new IllegalStateException("Could not compare methods", e);
311 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
312 * implemented {@link Augmentation} interface.
314 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
315 * @return Augmentation target - class which augmentation provides additional extensions.
317 static final Class<? extends Augmentable<?>> findAugmentationTarget(
318 final Class<? extends Augmentation<?>> augmentation) {
319 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
321 return opt.orElse(null);
324 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
325 // FIXME: rework this to work on EffectiveStatements
326 if (nodeSchema instanceof DataNodeContainer contaner) {
327 boolean haveAddressable = false;
328 boolean haveUnaddressable = false;
329 for (DataSchemaNode child : contaner.getChildNodes()) {
330 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
331 haveAddressable = true;
332 } else if (child instanceof ListSchemaNode list) {
333 if (list.getKeyDefinition().isEmpty()) {
334 haveUnaddressable = true;
336 haveAddressable = true;
338 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
339 || child instanceof TypedDataSchemaNode) {
340 haveUnaddressable = true;
341 } else if (child instanceof ChoiceSchemaNode choice) {
342 switch (computeChildAddressabilitySummary(choice)) {
343 case ADDRESSABLE -> haveAddressable = true;
344 case UNADDRESSABLE -> haveUnaddressable = true;
346 haveAddressable = true;
347 haveUnaddressable = true;
349 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
352 LOG.warn("Unhandled child node {}", child);
356 if (!haveAddressable) {
357 // Empty or all are unaddressable
358 return ChildAddressabilitySummary.UNADDRESSABLE;
361 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
362 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
363 return computeChildAddressabilitySummary(choice);
366 // No child nodes possible: return unaddressable
367 return ChildAddressabilitySummary.UNADDRESSABLE;
370 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
371 final ChoiceSchemaNode choice) {
372 boolean haveAddressable = false;
373 boolean haveUnaddressable = false;
374 for (CaseSchemaNode child : choice.getCases()) {
375 switch (computeChildAddressabilitySummary(child)) {
377 haveAddressable = true;
380 haveUnaddressable = true;
383 // A child is mixed, which means we are mixed, too
384 return ChildAddressabilitySummary.MIXED;
386 throw new IllegalStateException("Unhandled accessibility summary for " + child);
390 if (!haveAddressable) {
391 // Empty or all are unaddressable
392 return ChildAddressabilitySummary.UNADDRESSABLE;
395 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;