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 com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.collect.ImmutableCollection;
14 import com.google.common.collect.ImmutableSet;
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.lang.reflect.ParameterizedType;
21 import java.util.Arrays;
22 import java.util.HashSet;
23 import java.util.List;
25 import java.util.Optional;
27 import org.eclipse.jdt.annotation.NonNull;
28 import org.eclipse.jdt.annotation.Nullable;
29 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
30 import org.opendaylight.mdsal.binding.dom.codec.api.BindingNormalizedNodeCachingCodec;
31 import org.opendaylight.mdsal.binding.dom.codec.api.BindingStreamEventWriter;
32 import org.opendaylight.mdsal.binding.dom.codec.api.IncorrectNestingException;
33 import org.opendaylight.mdsal.binding.dom.codec.api.MissingClassInLoadingStrategyException;
34 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaException;
35 import org.opendaylight.mdsal.binding.dom.codec.api.MissingSchemaForClassException;
36 import org.opendaylight.mdsal.binding.model.api.Type;
37 import org.opendaylight.mdsal.binding.runtime.api.BindingRuntimeContext;
38 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
39 import org.opendaylight.mdsal.binding.runtime.api.RuntimeTypeContainer;
40 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
41 import org.opendaylight.yangtools.util.ClassLoaderUtils;
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.YangInstanceIdentifier.AugmentationIdentifier;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
52 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
53 import org.opendaylight.yangtools.yang.data.impl.schema.ImmutableNormalizedNodeStreamWriter;
54 import org.opendaylight.yangtools.yang.data.impl.schema.NormalizedNodeResult;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
58 abstract class DataContainerCodecContext<D extends DataObject, T extends RuntimeTypeContainer> extends NodeCodecContext
59 implements BindingDataObjectCodecTreeNode<D> {
60 private static final Logger LOG = LoggerFactory.getLogger(DataContainerCodecContext.class);
61 private static final VarHandle EVENT_STREAM_SERIALIZER;
65 EVENT_STREAM_SERIALIZER = MethodHandles.lookup().findVarHandle(DataContainerCodecContext.class,
66 "eventStreamSerializer", DataObjectSerializer.class);
67 } catch (NoSuchFieldException | IllegalAccessException e) {
68 throw new ExceptionInInitializerError(e);
72 private final @NonNull DataContainerCodecPrototype<T> prototype;
74 // Accessed via a VarHandle
75 @SuppressWarnings("unused")
76 private volatile DataObjectSerializer eventStreamSerializer;
78 DataContainerCodecContext(final DataContainerCodecPrototype<T> prototype) {
79 this.prototype = requireNonNull(prototype);
82 public final @NonNull T getType() {
83 return prototype.getType();
87 public final ChildAddressabilitySummary getChildAddressabilitySummary() {
88 return prototype.getChildAddressabilitySummary();
91 protected final QNameModule namespace() {
92 return prototype.getNamespace();
95 protected final CodecContextFactory factory() {
96 return prototype.getFactory();
100 protected YangInstanceIdentifier.PathArgument getDomPathArgument() {
101 return prototype.getYangArg();
105 * Returns nested node context using supplied YANG Instance Identifier.
107 * @param arg Yang Instance Identifier Argument
108 * @return Context of child
109 * @throws IllegalArgumentException If supplied argument does not represent valid child.
112 public abstract NodeCodecContext yangPathArgumentChild(YangInstanceIdentifier.PathArgument arg);
115 * Returns nested node context using supplied Binding Instance Identifier
116 * and adds YANG instance identifiers to supplied list.
118 * @param arg Binding Instance Identifier Argument
119 * @return Context of child or null if supplied {@code arg} does not represent valid child.
120 * @throws IllegalArgumentException If supplied argument does not represent valid child.
123 public DataContainerCodecContext<?, ?> bindingPathArgumentChild(final PathArgument arg,
124 final List<YangInstanceIdentifier.PathArgument> builder) {
125 final DataContainerCodecContext<?,?> child = streamChild(arg.getType());
126 if (builder != null) {
127 child.addYangPathArgument(arg,builder);
133 * Returns deserialized Binding Path Argument from YANG instance identifier.
135 protected PathArgument getBindingPathArgument(final YangInstanceIdentifier.PathArgument domArg) {
139 protected final PathArgument bindingArg() {
140 return prototype.getBindingArg();
143 @SuppressWarnings("unchecked")
145 public final Class<D> getBindingClass() {
146 return Class.class.cast(prototype.getBindingClass());
150 public abstract <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(Class<C> childClass);
153 * Returns child context as if it was walked by {@link BindingStreamEventWriter}. This means that to enter case, one
154 * must issue getChild(ChoiceClass).getChild(CaseClass).
156 * @param childClass child class
157 * @return Context of child or Optional.empty is supplied class is not applicable in context.
160 public abstract <C extends DataObject> Optional<DataContainerCodecContext<C,?>> possibleStreamChild(
161 Class<C> childClass);
164 public String toString() {
165 return getClass().getSimpleName() + " [" + prototype.getBindingClass() + "]";
169 public BindingNormalizedNodeCachingCodec<D> createCachingCodec(
170 final ImmutableCollection<Class<? extends BindingObject>> cacheSpecifier) {
171 if (cacheSpecifier.isEmpty()) {
172 return new NonCachingCodec<>(this);
174 return new CachingNormalizedNodeCodec<>(this, ImmutableSet.copyOf(cacheSpecifier));
177 protected final <V> @NonNull V childNonNull(final @Nullable V nullable,
178 final YangInstanceIdentifier.PathArgument child, final String message, final Object... args) {
179 if (nullable == null) {
180 throw childNullException(extractName(child), message, args);
185 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final QName child, final String message,
186 final Object... args) {
187 if (nullable == null) {
188 throw childNullException(child, message, args);
193 protected final <V> @NonNull V childNonNull(final @Nullable V nullable, final Class<?> childClass,
194 final String message, final Object... args) {
195 if (nullable == null) {
196 throw childNullException(childClass, message, args);
201 private IllegalArgumentException childNullException(final QName child, final String message, final Object... args) {
202 final QNameModule module = child.getModule();
203 if (!factory().getRuntimeContext().getEffectiveModelContext().findModule(module).isPresent()) {
204 throw new MissingSchemaException("Module " + module + " is not present in current schema context.");
206 throw IncorrectNestingException.create(message, args);
209 private IllegalArgumentException childNullException(final Class<?> childClass, final String message,
210 final Object... args) {
211 final BindingRuntimeContext runtimeContext = factory().getRuntimeContext();
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 throw new MissingSchemaForClassException(childClass);
223 runtimeContext.loadClass(Type.of(childClass));
224 } catch (final ClassNotFoundException e) {
225 throw new MissingClassInLoadingStrategyException(
226 "User supplied class " + childClass.getName() + " is not available in " + runtimeContext, e);
229 throw IncorrectNestingException.create(message, args);
232 private static QName extractName(final YangInstanceIdentifier.PathArgument child) {
233 if (child instanceof AugmentationIdentifier) {
234 final Set<QName> children = ((AugmentationIdentifier) child).getPossibleChildNames();
235 checkArgument(!children.isEmpty(), "Augmentation without childs must not be used in data");
236 return children.iterator().next();
238 return child.getNodeType();
241 final DataObjectSerializer eventStreamSerializer() {
242 final DataObjectSerializer existing = (DataObjectSerializer) EVENT_STREAM_SERIALIZER.getAcquire(this);
243 return existing != null ? existing : loadEventStreamSerializer();
246 // Split out to aid inlining
247 private DataObjectSerializer loadEventStreamSerializer() {
248 final DataObjectSerializer loaded = factory().getEventStreamSerializer(getBindingClass());
249 final Object witness = EVENT_STREAM_SERIALIZER.compareAndExchangeRelease(this, null, loaded);
250 return witness == null ? loaded : (DataObjectSerializer) witness;
254 public NormalizedNode serialize(final D data) {
255 final NormalizedNodeResult result = new NormalizedNodeResult();
256 // We create DOM stream writer which produces normalized nodes
257 final NormalizedNodeStreamWriter domWriter = ImmutableNormalizedNodeStreamWriter.from(result);
258 writeAsNormalizedNode(data, domWriter);
259 return result.getResult();
263 public void writeAsNormalizedNode(final D data, final NormalizedNodeStreamWriter writer) {
265 eventStreamSerializer().serialize(data, new BindingToNormalizedStreamWriter(this, writer));
266 } catch (final IOException e) {
267 throw new IllegalStateException("Failed to serialize Binding DTO",e);
271 static final <T extends NormalizedNode> @NonNull T checkDataArgument(final @NonNull Class<T> expectedType,
272 final NormalizedNode data) {
274 return expectedType.cast(requireNonNull(data));
275 } catch (ClassCastException e) {
276 throw new IllegalArgumentException("Expected " + expectedType.getSimpleName(), e);
280 // FIXME: MDSAL-780 replace this method with BindingRuntimeTypes-driven logic
281 static final Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
282 final String prefix) {
283 final String methodName = method.getName();
284 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
285 return Optional.empty();
288 final Class<?> returnType = method.getReturnType();
289 if (DataContainer.class.isAssignableFrom(returnType)) {
290 return optionalDataContainer(returnType);
291 } else if (List.class.isAssignableFrom(returnType)) {
292 return getYangModeledReturnType(method, 0);
293 } else if (Map.class.isAssignableFrom(returnType)) {
294 return getYangModeledReturnType(method, 1);
296 return Optional.empty();
299 @SuppressWarnings("checkstyle:illegalCatch")
300 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
301 final int parameterOffset) {
303 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(),
304 () -> genericParameter(method.getGenericReturnType(), parameterOffset)
305 .flatMap(result -> result instanceof Class ? optionalCast((Class<?>) result) : Optional.empty()));
306 } catch (Exception e) {
308 * It is safe to log this this exception on debug, since this
309 * method should not fail. Only failures are possible if the
312 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
314 return Optional.empty();
317 private static Optional<java.lang.reflect.Type> genericParameter(final java.lang.reflect.Type type,
319 if (type instanceof ParameterizedType parameterized) {
320 final var parameters = parameterized.getActualTypeArguments();
321 if (parameters.length > offset) {
322 return Optional.of(parameters[offset]);
325 return Optional.empty();
328 private static Optional<Class<? extends DataContainer>> optionalCast(final Class<?> type) {
329 return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty();
333 // FIXME: MDSAL-780: remove this method
334 static final Optional<Class<? extends DataContainer>> optionalDataContainer(final Class<?> type) {
335 return Optional.of(type.asSubclass(DataContainer.class));
340 * Determines if two augmentation classes or case classes represents same data.
343 * Two augmentations or cases could be substituted only if and if:
345 * <li>Both implements same interfaces</li>
346 * <li>Both have same children</li>
347 * <li>If augmentations: Both have same augmentation target class. Target class was generated for data node in a
349 * <li>If cases: Both are from same choice. Choice class was generated for data node in grouping.</li>
353 * <b>Explanation:</b>
354 * Binding Specification reuses classes generated for groupings as part of normal data tree, this classes from
355 * grouping could be used at various locations and user may not be aware of it and may use incorrect case or
356 * augmentation in particular subtree (via copy constructors, etc).
358 * @param potential Class which is potential substitution
359 * @param target Class which should be used at particular subtree
360 * @return true if and only if classes represents same data.
361 * @throws NullPointerException if any argument is {@code null}
363 // FIXME: MDSAL-785: this really should live in BindingRuntimeTypes and should not be based on reflection. The only
364 // user is binding-dom-codec and the logic could easily be performed on GeneratedType instead. For
365 // a particular world this boils down to a matrix, which can be calculated either on-demand or
366 // when we create BindingRuntimeTypes. Achieving that will bring us one step closer to being able
367 // to have a pre-compiled Binding Runtime.
368 @SuppressWarnings({ "rawtypes", "unchecked" })
369 static boolean isSubstitutionFor(final Class potential, final Class target) {
370 Set<Class> subImplemented = new HashSet<>(Arrays.asList(potential.getInterfaces()));
371 Set<Class> targetImplemented = new HashSet<>(Arrays.asList(target.getInterfaces()));
372 if (!subImplemented.equals(targetImplemented)) {
375 if (Augmentation.class.isAssignableFrom(potential)
376 && !BindingReflections.findAugmentationTarget(potential).equals(
377 BindingReflections.findAugmentationTarget(target))) {
380 for (Method potentialMethod : potential.getMethods()) {
381 if (Modifier.isStatic(potentialMethod.getModifiers())) {
382 // Skip any static methods, as we are not interested in those
387 Method targetMethod = target.getMethod(potentialMethod.getName(), potentialMethod.getParameterTypes());
388 if (!potentialMethod.getReturnType().equals(targetMethod.getReturnType())) {
391 } catch (NoSuchMethodException e) {
392 // Counterpart method is missing, so classes could not be substituted.
394 } catch (SecurityException e) {
395 throw new IllegalStateException("Could not compare methods", e);