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);
134 public abstract <C extends DataObject> CommonDataObjectCodecContext<C, ?> streamChild(Class<C> childClass);
137 public String toString() {
138 return getClass().getSimpleName() + " [" + getBindingClass() + "]";
141 static final <T extends DataObject, C extends DataContainerCodecContext<T, ?> & BindingNormalizedNodeCodec<T>>
142 @NonNull BindingNormalizedNodeCachingCodec<T> createCachingCodec(final C context,
143 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
144 return cacheSpecifier.isEmpty() ? new NonCachingCodec<>(context)
145 : new CachingNormalizedNodeCodec<>(context, ImmutableSet.copyOf(cacheSpecifier));
148 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
149 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
150 if (nullable == null) {
151 throw childNullException(child.getNodeType(), message, args);
156 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
157 final Object... args) {
158 if (nullable == null) {
159 throw childNullException(child, message, args);
164 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
165 final String message, final Object... args) {
166 if (nullable == null) {
167 throw childNullException(childClass, message, args);
173 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
174 final QNameModule module = child.getModule();
175 if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
176 return new MissingSchemaException("Module " + module + " is not present in current schema context.");
178 return new IncorrectNestingException(message, args);
182 private @NonNull IllegalArgumentException childNullException(final Class<?> childClass, final String message,
183 final Object... args) {
184 return childNullException(factory().getRuntimeContext(), childClass, message, args);
188 static @NonNull IllegalArgumentException childNullException(final BindingRuntimeContext runtimeContext,
189 final Class<?> childClass, final String message, final Object... args) {
190 final CompositeRuntimeType schema;
191 if (Augmentation.class.isAssignableFrom(childClass)) {
192 schema = runtimeContext.getAugmentationDefinition(childClass.asSubclass(Augmentation.class));
194 schema = runtimeContext.getSchemaDefinition(childClass);
196 if (schema == null) {
197 return new MissingSchemaForClassException(childClass);
201 runtimeContext.loadClass(Type.of(childClass));
202 } catch (final ClassNotFoundException e) {
203 return new MissingClassInLoadingStrategyException(
204 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
207 return new IncorrectNestingException(message, args);
210 final DataContainerSerializer eventStreamSerializer() {
211 final DataContainerSerializer existing = (DataContainerSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
212 return existing != null ? existing : loadEventStreamSerializer();
215 // Split out to aid inlining
216 private DataContainerSerializer loadEventStreamSerializer() {
217 final DataContainerSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
218 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
219 return witness == null ? loaded : (DataContainerSerializer) witness;
222 final @NonNull NormalizedNode serializeImpl(final @NonNull D data) {
223 final var result = new NormalizationResultHolder();
224 // We create DOM stream writer which produces normalized nodes
225 final var domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
227 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, domWriter));
228 } catch (final IOException e) {
229 throw new IllegalStateException("Failed to serialize Binding DTO",e);
231 return result.getResult().data();
234 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
235 final NormalizedNode data) {
237 return expectedType.cast(requireNonNull(data));
238 } catch (ClassCastException e) {
239 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
244 * Determines if two augmentation classes or case classes represents same data.
247 * Two augmentations or cases could be substituted only if and if:
249 * <li>Both implements same interfaces</li>
250 * <li>Both have same children</li>
251 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
253 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
257 * <b>Explanation:</b>
258 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
259 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
260 * augmentation in particular subtree (via copy constructors, etc).
262 * @param potential Class which is potential substitution
263 * @param target Class which should be used at particular subtree
264 * @return true if and only if classes represents same data.
265 * @throws NullPointerException if any argument is {@code null}
267 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
268 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
269 // a particular world this boils down to a matrix, which can be calculated either on-demand or
270 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
271 // to have a pre-compiled Binding Runtime.
272 @SuppressWarnings({ "rawtypes", "unchecked" })
273 static final boolean isSubstitutionFor(final Class potential, final Class target) {
274 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
275 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
276 if (!subImplemented.equals(targetImplemented)) {
279 if (Augmentation.class.isAssignableFrom(potential)
280 && !findAugmentationTarget(potential).equals(findAugmentationTarget(target))) {
283 for (Method potentialMethod : potential.getMethods()) {
284 if (Modifier.isStatic(potentialMethod.getModifiers())) {
285 // Skip any static methods, as we are not interested in those
290 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
291 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
294 } catch (NoSuchMethodException e) {
295 // Counterpart method is missing, so classes could not be substituted.
297 } catch (SecurityException e) {
298 throw new IllegalStateException("Could not compare methods", e);
305 * Find augmentation target class from concrete Augmentation class. This method uses first generic argument of
306 * implemented {@link Augmentation} interface.
308 * @param augmentation {@link Augmentation} subclass for which we want to determine augmentation target.
309 * @return Augmentation target - class which augmentation provides additional extensions.
311 static final Class<? extends Augmentable<?>> findAugmentationTarget(
312 final Class<? extends Augmentation<?>> augmentation) {
313 final Optional<Class<Augmentable<?>>> opt = ClassLoaderUtils.findFirstGenericArgument(augmentation,
315 return opt.orElse(null);
318 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(final Object nodeSchema) {
319 // FIXME: rework this to work on EffectiveStatements
320 if (nodeSchema instanceof DataNodeContainer contaner) {
321 boolean haveAddressable = false;
322 boolean haveUnaddressable = false;
323 for (DataSchemaNode child : contaner.getChildNodes()) {
324 if (child instanceof ContainerSchemaNode || child instanceof AugmentationSchemaNode) {
325 haveAddressable = true;
326 } else if (child instanceof ListSchemaNode list) {
327 if (list.getKeyDefinition().isEmpty()) {
328 haveUnaddressable = true;
330 haveAddressable = true;
332 } else if (child instanceof AnydataSchemaNode || child instanceof AnyxmlSchemaNode
333 || child instanceof TypedDataSchemaNode) {
334 haveUnaddressable = true;
335 } else if (child instanceof ChoiceSchemaNode choice) {
336 switch (computeChildAddressabilitySummary(choice)) {
337 case ADDRESSABLE -> haveAddressable = true;
338 case UNADDRESSABLE -> haveUnaddressable = true;
340 haveAddressable = true;
341 haveUnaddressable = true;
343 default -> throw new IllegalStateException("Unhandled accessibility summary for " + child);
346 LOG.warn("Unhandled child node {}", child);
350 if (!haveAddressable) {
351 // Empty or all are unaddressable
352 return ChildAddressabilitySummary.UNADDRESSABLE;
355 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;
356 } else if (nodeSchema instanceof ChoiceSchemaNode choice) {
357 return computeChildAddressabilitySummary(choice);
360 // No child nodes possible: return unaddressable
361 return ChildAddressabilitySummary.UNADDRESSABLE;
364 private static @NonNull ChildAddressabilitySummary computeChildAddressabilitySummary(
365 final ChoiceSchemaNode choice) {
366 boolean haveAddressable = false;
367 boolean haveUnaddressable = false;
368 for (CaseSchemaNode child : choice.getCases()) {
369 switch (computeChildAddressabilitySummary(child)) {
371 haveAddressable = true;
374 haveUnaddressable = true;
377 // A child is mixed, which means we are mixed, too
378 return ChildAddressabilitySummary.MIXED;
380 throw new IllegalStateException("Unhandled accessibility summary for " + child);
384 if (!haveAddressable) {
385 // Empty or all are unaddressable
386 return ChildAddressabilitySummary.UNADDRESSABLE;
389 return haveUnaddressable ? ChildAddressabilitySummary.MIXED : ChildAddressabilitySummary.ADDRESSABLE;