3b0d074c373d0fb268d0275f4169bf5c91a739a9
[mdsal.git] / binding / mdsal-binding-runtime-api / src / main / java / org / opendaylight / mdsal / binding / runtime / api / AbstractBindingRuntimeContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.runtime.api;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Iterables;
20 import java.util.AbstractMap.SimpleEntry;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.HashSet;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import java.util.Set;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
31 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
32 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
33 import org.opendaylight.mdsal.binding.model.api.Type;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
35 import org.opendaylight.yangtools.yang.binding.Action;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
40 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
41 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
43 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
55  * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
56  * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
57  *
58  * <p>Some of this information are for example list of all available children for cases
59  * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
60  * by additional models. Same goes for all possible augmentations.
61  */
62 @Beta
63 public abstract class AbstractBindingRuntimeContext implements BindingRuntimeContext {
64     private static final Logger LOG = LoggerFactory.getLogger(AbstractBindingRuntimeContext.class);
65
66     private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
67         new CacheLoader<QName, Class<?>>() {
68             @Override
69             public Class<?> load(final QName key) {
70                 final Optional<Type> identityType = getTypes().findIdentity(key);
71                 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
72                 try {
73                     return loadClass(identityType.get());
74                 } catch (final ClassNotFoundException e) {
75                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
76                 }
77             }
78         });
79
80     @Override
81     public final <T extends Augmentation<?>> AugmentationSchemaNode getAugmentationDefinition(final Class<T> augClass) {
82         return getTypes().findAugmentation(Type.of(augClass)).orElse(null);
83     }
84
85     @Override
86     public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
87         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
88             cls);
89         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
90         return (DataSchemaNode) getTypes().findSchema(Type.of(cls)).orElse(null);
91     }
92
93     @Override
94     public final DataSchemaNode findChildSchemaDefinition(final DataNodeContainer parentSchema,
95             final QNameModule parentNamespace, final Class<?> childClass) {
96         final DataSchemaNode origDef = getSchemaDefinition(childClass);
97         if (origDef == null) {
98             // Weird, the child does not have an associated definition
99             return null;
100         }
101
102         // Direct instantiation or use in same module in which grouping was defined.
103         final QName origName = origDef.getQName();
104         final DataSchemaNode sameName = parentSchema.dataChildByName(origName);
105         if (sameName != null) {
106             // Check if it is:
107             // - exactly same schema node, or
108             // - instantiated node was added via uses statement and is instantiation of same grouping
109             if (origDef.equals(sameName) || origDef.equals(getRootOriginalIfPossible(sameName))) {
110                 return sameName;
111             }
112
113             // Node has same name, but clearly is different
114             return null;
115         }
116
117         // We are looking for instantiation via uses in other module
118         final DataSchemaNode potential = parentSchema.dataChildByName(origName.bindTo(parentNamespace));
119         // We check if it is really instantiated from same definition as class was derived
120         if (potential != null && origDef.equals(getRootOriginalIfPossible(potential))) {
121             return potential;
122         }
123         return null;
124     }
125
126     private static @Nullable SchemaNode getRootOriginalIfPossible(final SchemaNode data) {
127         SchemaNode previous = null;
128         SchemaNode next = originalNodeOf(data);
129         while (next != null) {
130             previous = next;
131             next = originalNodeOf(next);
132         }
133         return previous;
134     }
135
136     @Override
137     public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
138         return (ActionDefinition) getTypes().findSchema(Type.of(cls)).orElse(null);
139     }
140
141     @Override
142     public final Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
143             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
144         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
145         checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
146         /*
147          * FIXME: Validate augmentation schema lookup
148          *
149          * Currently this algorithm, does not verify if instantiated child nodes
150          * are real one derived from augmentation schema. The problem with
151          * full validation is, if user used copy builders, he may use
152          * augmentation which was generated for different place.
153          *
154          * If this augmentations have same definition, we emit same identifier
155          * with data and it is up to underlying user to validate data.
156          *
157          */
158         final Set<QName> childNames = new HashSet<>();
159         final Set<DataSchemaNode> realChilds = new HashSet<>();
160         for (final DataSchemaNode child : origSchema.getChildNodes()) {
161             final DataSchemaNode dataChildQNname = target.dataChildByName(child.getQName());
162             final String childLocalName = child.getQName().getLocalName();
163             if (dataChildQNname == null) {
164                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
165                     if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
166                         realChilds.add(dataSchemaNode);
167                         childNames.add(dataSchemaNode.getQName());
168                     }
169                 }
170             } else {
171                 realChilds.add(dataChildQNname);
172                 childNames.add(child.getQName());
173             }
174         }
175
176         final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
177         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
178         return new SimpleEntry<>(identifier, proxy);
179     }
180
181     @Override
182     public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
183             final Class<?> childClass) {
184         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
185         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
186
187         /* FIXME: Make sure that if there are multiple augmentations of same
188          * named case, with same structure we treat it as equals
189          * this is due property of Binding specification and copy builders
190          * that user may be unaware that he is using incorrect case
191          * which was generated for choice inside grouping.
192          */
193         return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
194     }
195
196     @Override
197     public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
198         return getTypeWithSchema(getTypes(), Type.of(type));
199     }
200
201     private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
202             final Type referencedType) {
203         final WithStatus schema = types.findSchema(referencedType).orElseThrow(
204             () -> new NullPointerException("Failed to find schema for type " + referencedType));
205         final Type definedType = types.findType(schema).orElseThrow(
206             () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
207
208         if (definedType instanceof GeneratedTypeBuilder) {
209             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
210         }
211         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
212         return new SimpleEntry<>((GeneratedType) definedType, schema);
213     }
214
215     @Override
216     public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
217         return getChoiceCaseChildren(getTypes(), schema);
218     }
219
220     private static @NonNull ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final BindingRuntimeTypes types,
221             final DataNodeContainer schema) {
222         final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
223
224         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
225             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
226             final Optional<Type> optType = types.findType(originalChoice);
227             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
228             final Type choiceType = optType.get();
229
230             for (Type caze : types.findCases(choiceType)) {
231                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
232                 final HashSet<Type> caseChildren = new HashSet<>();
233                 if (caze instanceof GeneratedTypeBuilder) {
234                     caze = ((GeneratedTypeBuilder) caze).build();
235                 }
236                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
237                 for (final Type caseChild : caseChildren) {
238                     childToCase.put(caseChild, caseIdentifier);
239                 }
240             }
241         }
242         return ImmutableMap.copyOf(childToCase);
243     }
244
245     @Override
246     public final Set<Class<?>> getCases(final Class<?> choice) {
247         final Collection<Type> cazes = getTypes().findCases(Type.of(choice));
248         final Set<Class<?>> ret = new HashSet<>(cazes.size());
249         for (final Type caze : cazes) {
250             try {
251                 ret.add(loadClass(caze));
252             } catch (final ClassNotFoundException e) {
253                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
254             }
255         }
256         return ret;
257     }
258
259     @Override
260     public final Class<?> getClassForSchema(final SchemaNode childSchema) {
261         final SchemaNode origSchema = getOriginalSchema(childSchema);
262         final Optional<Type> clazzType = getTypes().findType(origSchema);
263         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
264             childSchema, origSchema);
265
266         try {
267             return loadClass(clazzType.get());
268         } catch (final ClassNotFoundException e) {
269             throw new IllegalStateException(e);
270         }
271     }
272
273     @Override
274     public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
275             final DataNodeContainer container) {
276         if (container instanceof AugmentationTarget) {
277             final var augmentations = ((AugmentationTarget) container).getAvailableAugmentations();
278             if (!augmentations.isEmpty()) {
279                 final var identifierToType = new HashMap<AugmentationIdentifier, Type>();
280                 final var types = getTypes();
281                 for (var augment : augmentations) {
282                     types.findOriginalAugmentationType(augment).ifPresent(augType -> {
283                         identifierToType.put(getAugmentationIdentifier(augment), augType);
284                     });
285                 }
286                 return ImmutableMap.copyOf(identifierToType);
287             }
288         }
289         return ImmutableMap.of();
290     }
291
292     @Override
293     public final Class<?> getIdentityClass(final QName input) {
294         return identityClasses.getUnchecked(input);
295     }
296
297     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
298         // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
299         return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
300             .collect(ImmutableSet.toImmutableSet()));
301     }
302
303     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
304         for (final MethodSignature definition : type.getMethodDefinitions()) {
305             Type childType = definition.getReturnType();
306             if (childType instanceof ParameterizedType) {
307                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
308             }
309             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
310                 collection.add(childType);
311             }
312         }
313         for (final Type parent : type.getImplements()) {
314             if (parent instanceof GeneratedType) {
315                 collectAllContainerTypes((GeneratedType) parent, collection);
316             }
317         }
318         return collection;
319     }
320
321     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
322         @SuppressWarnings("unchecked")
323         final T original = (T) originalNodeOf(choice);
324         if (original != null) {
325             return original;
326         }
327         return choice;
328     }
329
330     private static @NonNull Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
331             final CaseSchemaNode originalDefinition) {
332         CaseSchemaNode potential = instantiatedChoice.findCase(originalDefinition.getQName()).orElse(null);
333         if (originalDefinition.equals(potential)) {
334             return Optional.of(potential);
335         }
336         if (potential != null) {
337             SchemaNode potentialRoot = originalNodeOf(potential);
338             if (originalDefinition.equals(potentialRoot)) {
339                 return Optional.of(potential);
340             }
341         }
342
343         // We try to find case by name, then lookup its root definition
344         // and compare it with original definition
345         // This solves case, if choice was inside grouping
346         // which was used in different module and thus namespaces are
347         // different, but local names are still same.
348         //
349         // Still we need to check equality of definition, because local name is not
350         // sufficient to uniquelly determine equality of cases
351         //
352         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
353             if (originalDefinition.equals(originalNodeOf(caze))) {
354                 return Optional.of(caze);
355             }
356         }
357         return Optional.empty();
358     }
359
360     private static @Nullable SchemaNode originalNodeOf(final SchemaNode node) {
361         return node instanceof DerivableSchemaNode ? ((DerivableSchemaNode) node).getOriginal().orElse(null) : null;
362     }
363 }