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