2 * Copyright (c) 2023 PANTHEON.tech, s.r.o. 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 com.google.common.base.Verify.verify;
12 import static com.google.common.base.Verify.verifyNotNull;
13 import static java.util.Objects.requireNonNull;
15 import com.google.common.collect.ImmutableMap;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.ParameterizedType;
18 import java.util.HashMap;
19 import java.util.List;
21 import java.util.Optional;
22 import org.eclipse.jdt.annotation.NonNull;
23 import org.eclipse.jdt.annotation.Nullable;
24 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
25 import org.opendaylight.mdsal.binding.runtime.api.ChoiceRuntimeType;
26 import org.opendaylight.mdsal.binding.runtime.api.CompositeRuntimeType;
27 import org.opendaylight.mdsal.binding.runtime.api.ContainerLikeRuntimeType;
28 import org.opendaylight.mdsal.binding.runtime.api.ContainerRuntimeType;
29 import org.opendaylight.mdsal.binding.runtime.api.ListRuntimeType;
30 import org.opendaylight.yangtools.util.ClassLoaderUtils;
31 import org.opendaylight.yangtools.binding.lib.ChoiceIn;
32 import org.opendaylight.yangtools.binding.lib.DataContainer;
33 import org.opendaylight.yangtools.binding.lib.DataObject;
34 import org.opendaylight.yangtools.binding.lib.DataObjectStep;
35 import org.opendaylight.yangtools.binding.lib.InstanceIdentifier;
36 import org.opendaylight.yangtools.binding.lib.OpaqueObject;
37 import org.opendaylight.yangtools.binding.lib.contract.Naming;
38 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
39 import org.opendaylight.yangtools.yang.model.api.AddedByUsesAware;
40 import org.opendaylight.yangtools.yang.model.api.meta.EffectiveStatement;
41 import org.opendaylight.yangtools.yang.model.api.stmt.PresenceEffectiveStatement;
42 import org.slf4j.Logger;
43 import org.slf4j.LoggerFactory;
46 * Analysis of a {@link DataContainer} specialization class. This includes things needed for
47 * {@link DataContainerCodecContext}'s methods as well as the appropriate run-time generated class.
49 final class DataContainerAnalysis<R extends CompositeRuntimeType> {
50 private static final Logger LOG = LoggerFactory.getLogger(DataContainerAnalysis.class);
52 // Needed for DataContainerCodecContext
53 final @NonNull ImmutableMap<Class<?>, DataContainerPrototype<?, ?>> byStreamClass;
54 final @NonNull ImmutableMap<Class<?>, DataContainerPrototype<?, ?>> byBindingArgClass;
55 final @NonNull ImmutableMap<NodeIdentifier, CodecContextSupplier> byYang;
56 final @NonNull ImmutableMap<String, ValueNodeCodecContext> leafNodes;
58 // Needed for generated classes
59 final @NonNull ImmutableMap<Method, ValueNodeCodecContext> leafContexts;
60 final @NonNull ImmutableMap<Class<?>, PropertyInfo> daoProperties;
62 DataContainerAnalysis(final CommonDataObjectCodecPrototype<R> prototype) {
63 this(prototype.javaClass(), prototype.runtimeType(), prototype.contextFactory(), null);
66 DataContainerAnalysis(final CommonDataObjectCodecPrototype<R> prototype,
67 final Class<? extends DataObject> caseClass) {
68 this(prototype.javaClass(), prototype.runtimeType(), prototype.contextFactory(), requireNonNull(caseClass));
71 DataContainerAnalysis(final Class<?> bindingClass, final R runtimeType, final CodecContextFactory factory,
72 final @Nullable Class<? extends DataObject> caseClass) {
73 leafContexts = factory.getLeafNodes(bindingClass, runtimeType.statement());
75 // Reflection-based on the passed class
76 final var clsToMethod = getChildrenClassToMethod(bindingClass);
78 // Indexing part: be very careful around what gets done when
79 final var byYangBuilder = new HashMap<NodeIdentifier, CodecContextSupplier>();
81 // Step 1: add leaf children
82 var leafBuilder = ImmutableMap.<String, ValueNodeCodecContext>builderWithExpectedSize(leafContexts.size());
83 for (var leaf : leafContexts.values()) {
84 leafBuilder.put(leaf.getSchema().getQName().getLocalName(), leaf);
85 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
87 leafNodes = leafBuilder.build();
89 final var byBindingArgClassBuilder = new HashMap<Class<?>, DataContainerPrototype<?, ?>>();
90 final var byStreamClassBuilder = new HashMap<Class<?>, DataContainerPrototype<?, ?>>();
91 final var daoPropertiesBuilder = new HashMap<Class<?>, PropertyInfo>();
92 for (var childDataObj : clsToMethod.entrySet()) {
93 final var method = childDataObj.getValue();
94 verify(!method.isDefault(), "Unexpected default method %s in %s", method, bindingClass);
96 final var retClass = childDataObj.getKey();
97 if (OpaqueObject.class.isAssignableFrom(retClass)) {
98 // Filter OpaqueObjects, they are not containers
102 // Record getter method
103 daoPropertiesBuilder.put(retClass, new PropertyInfo.Getter(method));
105 final var childProto = getChildPrototype(runtimeType, factory, caseClass, retClass);
106 byStreamClassBuilder.put(childProto.javaClass(), childProto);
107 byYangBuilder.put(childProto.yangArg(), childProto);
109 if (childProto instanceof ChoiceCodecPrototype<?> choiceProto) {
110 for (var cazeChild : choiceProto.getCodecContext().getCaseChildrenClasses()) {
111 byBindingArgClassBuilder.put(cazeChild, choiceProto);
116 // Snapshot before below processing
117 byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
119 // Slight footprint optimization: we do not want to copy byStreamClass, as that would force its entrySet view
120 // to be instantiated. Furthermore the two maps can easily end up being equal -- hence we can reuse
121 // byStreamClass for the purposes of both.
122 byBindingArgClassBuilder.putAll(byStreamClassBuilder);
123 byBindingArgClass = byStreamClassBuilder.equals(byBindingArgClassBuilder) ? byStreamClass
124 : ImmutableMap.copyOf(byBindingArgClassBuilder);
126 // Find all non-default nonnullFoo() methods and update the corresponding property info
127 for (var entry : getChildrenClassToNonnullMethod(bindingClass).entrySet()) {
128 final var method = entry.getValue();
129 if (!method.isDefault()) {
130 daoPropertiesBuilder.compute(entry.getKey(), (key, value) -> new PropertyInfo.GetterAndNonnull(
131 verifyNotNull(value, "No getter for %s", key).getterMethod(), method));
135 // At this point all indexing is done: byYangBuilder should not be referenced
136 byYang = ImmutableMap.copyOf(byYangBuilder);
137 daoProperties = ImmutableMap.copyOf(daoPropertiesBuilder);
140 private static @NonNull DataContainerPrototype<?, ?> getChildPrototype(final CompositeRuntimeType type,
141 final CodecContextFactory factory, final @Nullable Class<? extends DataObject> caseClass,
142 final Class<? extends DataContainer> childClass) {
143 final var child = type.bindingChild(JavaTypeName.create(childClass));
145 throw DataContainerCodecContext.childNullException(factory.getRuntimeContext(), childClass,
146 "Node %s does not have child named %s", type, childClass);
149 if (child instanceof ChoiceRuntimeType choice) {
150 return new ChoiceCodecPrototype<>(factory, choice, childClass.asSubclass(ChoiceIn.class));
153 final var item = createItem(caseClass, childClass, child.statement());
154 if (child instanceof ContainerLikeRuntimeType containerLike) {
155 if (child instanceof ContainerRuntimeType container
156 && container.statement().findFirstEffectiveSubstatement(PresenceEffectiveStatement.class).isEmpty()) {
157 return new StructuralContainerCodecPrototype(item, container, factory);
159 return new ContainerLikeCodecPrototype(item, containerLike, factory);
160 } else if (child instanceof ListRuntimeType list) {
161 return list.keyType() != null ? new MapCodecPrototype(item, list, factory)
162 : new ListCodecPrototype(item, list, factory);
164 throw new UnsupportedOperationException("Unhandled type " + child);
168 // FIXME: MDSAL-697: move this method into BindingRuntimeContext
169 // This method is only called from loadChildPrototype() and exists only to be overridden by
170 // CaseNodeCodecContext. Since we are providing childClass and our schema to BindingRuntimeContext and
171 // receiving childSchema from it via findChildSchemaDefinition, we should be able to receive the equivalent
172 // of Map.Entry<Item, DataSchemaNode>, along with the override we create here. One more input we may need to
173 // provide is our bindingClass().
174 private static @NonNull DataObjectStep<?> createItem(final @Nullable Class<? extends DataObject> caseClass,
175 final Class<?> childClass, final EffectiveStatement<?, ?> childSchema) {
176 return caseClass != null && childSchema instanceof AddedByUsesAware aware && aware.isAddedByUses()
177 ? InstanceIdentifier.createStep((Class) caseClass, (Class) childClass)
178 : InstanceIdentifier.createStep((Class) childClass);
181 // FIXME: MDSAL-780: these methods perform analytics using java.lang.reflect to acquire the basic shape of the
182 // class. This is not exactly AOT friendly, as most of the information should be provided by
183 // CompositeRuntimeType.
185 // As as first cut, CompositeRuntimeType should provide the mapping between YANG children and the
186 // corresponding GETTER_PREFIX/NONNULL_PREFIX method names, If we have that, the use in this
187 // class should be fine.
189 // The second cut is binding the actual Method invocations, which is fine here, as this class is
190 // all about having a run-time generated class. AOT would be providing an alternative, where the
191 // equivalent class would be generated at compile-time and hence would bind to the methods
192 // directly -- and AOT equivalent of this class would really be a compile-time generated registry
193 // to those classes' entry points.
196 * Scans supplied class and returns an iterable of all data children classes.
198 * @param type YANG Modeled Entity derived from DataContainer
199 * @return Iterable of all data children, which have YANG modeled entity
201 private static Map<Class<? extends DataContainer>, Method> getChildrenClassToMethod(final Class<?> type) {
202 return getChildClassToMethod(type, Naming.GETTER_PREFIX);
205 private static Map<Class<? extends DataContainer>, Method> getChildrenClassToNonnullMethod(final Class<?> type) {
206 return getChildClassToMethod(type, Naming.NONNULL_PREFIX);
209 private static Map<Class<? extends DataContainer>, Method> getChildClassToMethod(final Class<?> type,
210 final String prefix) {
211 checkArgument(type != null, "Target type must not be null");
212 checkArgument(DataContainer.class.isAssignableFrom(type), "Supplied type %s must be derived from DataContainer",
214 final var ret = new HashMap<Class<? extends DataContainer>, Method>();
215 for (Method method : type.getMethods()) {
216 getYangModeledReturnType(method, prefix).ifPresent(entity -> ret.put(entity, method));
221 static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
222 final String prefix) {
223 final String methodName = method.getName();
224 if ("getClass".equals(methodName) || !methodName.startsWith(prefix) || method.getParameterCount() > 0) {
225 return Optional.empty();
228 final Class<?> returnType = method.getReturnType();
229 if (DataContainer.class.isAssignableFrom(returnType)) {
230 return optionalDataContainer(returnType);
231 } else if (List.class.isAssignableFrom(returnType)) {
232 return getYangModeledReturnType(method, 0);
233 } else if (Map.class.isAssignableFrom(returnType)) {
234 return getYangModeledReturnType(method, 1);
236 return Optional.empty();
239 @SuppressWarnings("checkstyle:illegalCatch")
240 private static Optional<Class<? extends DataContainer>> getYangModeledReturnType(final Method method,
241 final int parameterOffset) {
243 return ClassLoaderUtils.callWithClassLoader(method.getDeclaringClass().getClassLoader(),
244 () -> genericParameter(method.getGenericReturnType(), parameterOffset)
245 .flatMap(result -> result instanceof Class ? optionalCast((Class<?>) result) : Optional.empty()));
246 } catch (Exception e) {
248 * It is safe to log this this exception on debug, since this
249 * method should not fail. Only failures are possible if the
252 LOG.debug("Unable to find YANG modeled return type for {}", method, e);
254 return Optional.empty();
257 private static Optional<java.lang.reflect.Type> genericParameter(final java.lang.reflect.Type type,
259 if (type instanceof ParameterizedType parameterized) {
260 final var parameters = parameterized.getActualTypeArguments();
261 if (parameters.length > offset) {
262 return Optional.of(parameters[offset]);
265 return Optional.empty();
268 private static Optional<Class<? extends DataContainer>> optionalCast(final Class<?> type) {
269 return DataContainer.class.isAssignableFrom(type) ? optionalDataContainer(type) : Optional.empty();
272 private static Optional<Class<? extends DataContainer>> optionalDataContainer(final Class<?> type) {
273 return Optional.of(type.asSubclass(DataContainer.class));