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