920d11546b67dce331ec1c05c9c8d4828f9450a6
[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.DefaultType;
31 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
32 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
33 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
34 import org.opendaylight.mdsal.binding.model.api.Type;
35 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
36 import org.opendaylight.yangtools.yang.binding.Action;
37 import org.opendaylight.yangtools.yang.binding.Augmentation;
38 import org.opendaylight.yangtools.yang.common.QName;
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.DocumentedNode.WithStatus;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
51 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
52 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55
56 /**
57  * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
58  * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
59  *
60  * <p>Some of this information are for example list of all available children for cases
61  * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
62  * by additional models. Same goes for all possible augmentations.
63  */
64 @Beta
65 public abstract class AbstractBindingRuntimeContext implements BindingRuntimeContext {
66     private static final Logger LOG = LoggerFactory.getLogger(AbstractBindingRuntimeContext.class);
67
68     private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
69         new CacheLoader<QName, Class<?>>() {
70             @Override
71             public Class<?> load(final QName key) {
72                 final Optional<Type> identityType = getTypes().findIdentity(key);
73                 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
74                 try {
75                     return loadClass(identityType.get());
76                 } catch (final ClassNotFoundException e) {
77                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
78                 }
79             }
80         });
81
82     /**
83      * Returns schema of augmentation.
84      *
85      * <p>Returned schema is schema definition from which augmentation class was generated.
86      * This schema is isolated from other augmentations. This means it contains
87      * augmentation definition as was present in original YANG module.
88      *
89      * <p>Children of returned schema does not contain any additional augmentations,
90      * which may be present in runtime for them, thus returned schema is unsuitable
91      * for use for validation of data.
92      *
93      * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
94      * full model for child nodes, you should use method
95      * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
96      * which will return augmentation schema derived from supplied augmentation target
97      * schema.
98      *
99      * @param augClass Augmentation class
100      * @return Schema of augmentation or null if augmentaiton is not known in this context
101      * @throws IllegalArgumentException If supplied class is not an augmentation
102      */
103     @Override
104     public final @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
105         checkArgument(Augmentation.class.isAssignableFrom(augClass),
106             "Class %s does not represent augmentation", augClass);
107         return getTypes().findAugmentation(DefaultType.of(augClass)).orElse(null);
108     }
109
110     /**
111      * Returns defining {@link DataSchemaNode} for supplied class.
112      *
113      * <p>Returned schema is schema definition from which class was generated.
114      * This schema may be isolated from augmentations, if supplied class
115      * represent node, which was child of grouping or augmentation.
116      *
117      * <p>For getting augmentation schema from augmentation class use
118      * {@link #getAugmentationDefinition(Class)} instead.
119      *
120      * @param cls Class which represents list, container, choice or case.
121      * @return Schema node, from which class was generated.
122      */
123     @Override
124     public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
125         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
126             cls);
127         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
128         return (DataSchemaNode) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
129     }
130
131     @Override
132     public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
133         return (ActionDefinition) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
134     }
135
136     @Override
137     public final Absolute getActionIdentifier(final Class<? extends Action<?, ?, ?>> cls) {
138         return getTypes().findSchemaNodeIdentifier(DefaultType.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.getDataChildByName(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     /**
182      * Returns resolved case schema for supplied class.
183      *
184      * @param schema Resolved parent choice schema
185      * @param childClass Class representing case.
186      * @return Optionally a resolved case schema,.empty if the choice is not legal in
187      *         the given context.
188      * @throws IllegalArgumentException If supplied class does not represent case.
189      */
190     @Override
191     public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
192             final Class<?> childClass) {
193         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
194         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
195
196         /* FIXME: Make sure that if there are multiple augmentations of same
197          * named case, with same structure we treat it as equals
198          * this is due property of Binding specification and copy builders
199          * that user may be unaware that he is using incorrect case
200          * which was generated for choice inside grouping.
201          */
202         return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
203     }
204
205     /**
206      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
207      * from which supplied class was generated. Returned schema may be augmented with
208      * additional information, which was not available at compile type
209      * (e.g. third party augmentations).
210      *
211      * @param type Binding Class for which schema should be retrieved.
212      * @return Instance of generated type (definition of Java API), along with
213      *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
214      *     which was used to generate supplied class.
215      */
216     @Override
217     public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
218         return getTypeWithSchema(getTypes(), DefaultType.of(type));
219     }
220
221     private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
222             final Type referencedType) {
223         final WithStatus schema = types.findSchema(referencedType).orElseThrow(
224             () -> new NullPointerException("Failed to find schema for type " + referencedType));
225         final Type definedType = types.findType(schema).orElseThrow(
226             () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
227
228         if (definedType instanceof GeneratedTypeBuilder) {
229             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
230         }
231         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
232         return new SimpleEntry<>((GeneratedType) definedType, schema);
233     }
234
235     @Override
236     public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
237         return getChoiceCaseChildren(getTypes(), schema);
238     }
239
240     private static @NonNull ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final BindingRuntimeTypes types,
241             final DataNodeContainer schema) {
242         final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
243
244         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
245             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
246             final Optional<Type> optType = types.findType(originalChoice);
247             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
248             final Type choiceType = optType.get();
249
250             for (Type caze : types.findCases(choiceType)) {
251                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
252                 final HashSet<Type> caseChildren = new HashSet<>();
253                 if (caze instanceof GeneratedTypeBuilder) {
254                     caze = ((GeneratedTypeBuilder) caze).build();
255                 }
256                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
257                 for (final Type caseChild : caseChildren) {
258                     childToCase.put(caseChild, caseIdentifier);
259                 }
260             }
261         }
262         return ImmutableMap.copyOf(childToCase);
263     }
264
265     @Override
266     public final Set<Class<?>> getCases(final Class<?> choice) {
267         final Collection<Type> cazes = getTypes().findCases(DefaultType.of(choice));
268         final Set<Class<?>> ret = new HashSet<>(cazes.size());
269         for (final Type caze : cazes) {
270             try {
271                 ret.add(loadClass(caze));
272             } catch (final ClassNotFoundException e) {
273                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
274             }
275         }
276         return ret;
277     }
278
279     @Override
280     public final Class<?> getClassForSchema(final SchemaNode childSchema) {
281         final SchemaNode origSchema = getOriginalSchema(childSchema);
282         final Optional<Type> clazzType = getTypes().findType(origSchema);
283         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
284             childSchema, origSchema);
285
286         try {
287             return loadClass(clazzType.get());
288         } catch (final ClassNotFoundException e) {
289             throw new IllegalStateException(e);
290         }
291     }
292
293     @Override
294     public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
295             final DataNodeContainer container) {
296         final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
297         if (container instanceof AugmentationTarget) {
298             final BindingRuntimeTypes types = getTypes();
299             for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
300                 // Augmentation must have child nodes if is to be used with Binding classes
301                 AugmentationSchemaNode augOrig = augment;
302                 while (augOrig.getOriginalDefinition().isPresent()) {
303                     augOrig = augOrig.getOriginalDefinition().get();
304                 }
305
306                 if (!augment.getChildNodes().isEmpty()) {
307                     final Optional<Type> augType = types.findType(augOrig);
308                     if (augType.isPresent()) {
309                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
310                     }
311                 }
312             }
313         }
314
315         return ImmutableMap.copyOf(identifierToType);
316     }
317
318     @Override
319     public final Class<?> getIdentityClass(final QName input) {
320         return identityClasses.getUnchecked(input);
321     }
322
323     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
324         // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
325         return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
326             .collect(ImmutableSet.toImmutableSet()));
327     }
328
329     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
330         for (final MethodSignature definition : type.getMethodDefinitions()) {
331             Type childType = definition.getReturnType();
332             if (childType instanceof ParameterizedType) {
333                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
334             }
335             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
336                 collection.add(childType);
337             }
338         }
339         for (final Type parent : type.getImplements()) {
340             if (parent instanceof GeneratedType) {
341                 collectAllContainerTypes((GeneratedType) parent, collection);
342             }
343         }
344         return collection;
345     }
346
347     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
348         @SuppressWarnings("unchecked")
349         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
350         if (original != null) {
351             return original;
352         }
353         return choice;
354     }
355
356     private static @NonNull Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
357             final CaseSchemaNode originalDefinition) {
358         CaseSchemaNode potential = instantiatedChoice.findCase(originalDefinition.getQName()).orElse(null);
359         if (originalDefinition.equals(potential)) {
360             return Optional.of(potential);
361         }
362         if (potential != null) {
363             SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
364             if (originalDefinition.equals(potentialRoot)) {
365                 return Optional.of(potential);
366             }
367         }
368
369         // We try to find case by name, then lookup its root definition
370         // and compare it with original definition
371         // This solves case, if choice was inside grouping
372         // which was used in different module and thus namespaces are
373         // different, but local names are still same.
374         //
375         // Still we need to check equality of definition, because local name is not
376         // sufficient to uniquelly determine equality of cases
377         //
378         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
379             if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
380                 return Optional.of(caze);
381             }
382         }
383         return Optional.empty();
384     }
385 }