Bump yangtools to 5.0.0-SNAPSHOT
[mdsal.git] / binding / mdsal-binding-runtime-api / src / main / java / org / opendaylight / 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.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.base.MoreObjects;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableMap;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import java.util.AbstractMap.SimpleEntry;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.HashSet;
25 import java.util.Map;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.Set;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.mdsal.binding.model.api.DefaultType;
32 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
33 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
34 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
35 import org.opendaylight.mdsal.binding.model.api.Type;
36 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
37 import org.opendaylight.yangtools.yang.binding.Action;
38 import org.opendaylight.yangtools.yang.binding.Augmentation;
39 import org.opendaylight.yangtools.yang.common.QName;
40 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
41 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
42 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
44 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
47 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
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.TypeDefinition;
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 getStrategy().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 Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
138             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
139         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
140         checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
141         /*
142          * FIXME: Validate augmentation schema lookup
143          *
144          * Currently this algorithm, does not verify if instantiated child nodes
145          * are real one derived from augmentation schema. The problem with
146          * full validation is, if user used copy builders, he may use
147          * augmentation which was generated for different place.
148          *
149          * If this augmentations have same definition, we emit same identifier
150          * with data and it is up to underlying user to validate data.
151          *
152          */
153         final Set<QName> childNames = new HashSet<>();
154         final Set<DataSchemaNode> realChilds = new HashSet<>();
155         for (final DataSchemaNode child : origSchema.getChildNodes()) {
156             final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
157             final String childLocalName = child.getQName().getLocalName();
158             if (dataChildQNname == null) {
159                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
160                     if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
161                         realChilds.add(dataSchemaNode);
162                         childNames.add(dataSchemaNode.getQName());
163                     }
164                 }
165             } else {
166                 realChilds.add(dataChildQNname);
167                 childNames.add(child.getQName());
168             }
169         }
170
171         final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
172         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
173         return new SimpleEntry<>(identifier, proxy);
174     }
175
176     /**
177      * Returns resolved case schema for supplied class.
178      *
179      * @param schema Resolved parent choice schema
180      * @param childClass Class representing case.
181      * @return Optionally a resolved case schema,.empty if the choice is not legal in
182      *         the given context.
183      * @throws IllegalArgumentException If supplied class does not represent case.
184      */
185     @Override
186     public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
187             final Class<?> childClass) {
188         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
189         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
190
191         /* FIXME: Make sure that if there are multiple augmentations of same
192          * named case, with same structure we treat it as equals
193          * this is due property of Binding specification and copy builders
194          * that user may be unaware that he is using incorrect case
195          * which was generated for choice inside grouping.
196          */
197         return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
198     }
199
200     /**
201      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
202      * from which supplied class was generated. Returned schema may be augmented with
203      * additional information, which was not available at compile type
204      * (e.g. third party augmentations).
205      *
206      * @param type Binding Class for which schema should be retrieved.
207      * @return Instance of generated type (definition of Java API), along with
208      *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
209      *     which was used to generate supplied class.
210      */
211     @Override
212     public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
213         return getTypeWithSchema(getTypes(), DefaultType.of(type));
214     }
215
216     private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
217             final Type referencedType) {
218         final WithStatus schema = types.findSchema(referencedType).orElseThrow(
219             () -> new NullPointerException("Failed to find schema for type " + referencedType));
220         final Type definedType = types.findType(schema).orElseThrow(
221             () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
222
223         if (definedType instanceof GeneratedTypeBuilder) {
224             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
225         }
226         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
227         return new SimpleEntry<>((GeneratedType) definedType, schema);
228     }
229
230     @Override
231     public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
232         return getChoiceCaseChildren(getTypes(), schema);
233     }
234
235     private static @NonNull ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final BindingRuntimeTypes types,
236             final DataNodeContainer schema) {
237         final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
238
239         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
240             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
241             final Optional<Type> optType = types.findType(originalChoice);
242             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
243             final Type choiceType = optType.get();
244
245             for (Type caze : types.findCases(choiceType)) {
246                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
247                 final HashSet<Type> caseChildren = new HashSet<>();
248                 if (caze instanceof GeneratedTypeBuilder) {
249                     caze = ((GeneratedTypeBuilder) caze).build();
250                 }
251                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
252                 for (final Type caseChild : caseChildren) {
253                     childToCase.put(caseChild, caseIdentifier);
254                 }
255             }
256         }
257         return ImmutableMap.copyOf(childToCase);
258     }
259
260     @Override
261     public final Set<Class<?>> getCases(final Class<?> choice) {
262         final Collection<Type> cazes = getTypes().findCases(DefaultType.of(choice));
263         final Set<Class<?>> ret = new HashSet<>(cazes.size());
264         for (final Type caze : cazes) {
265             try {
266                 ret.add(getStrategy().loadClass(caze));
267             } catch (final ClassNotFoundException e) {
268                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
269             }
270         }
271         return ret;
272     }
273
274     @Override
275     public final Class<?> getClassForSchema(final SchemaNode childSchema) {
276         final SchemaNode origSchema = getOriginalSchema(childSchema);
277         final Optional<Type> clazzType = getTypes().findType(origSchema);
278         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
279             childSchema, origSchema);
280
281         try {
282             return getStrategy().loadClass(clazzType.get());
283         } catch (final ClassNotFoundException e) {
284             throw new IllegalStateException(e);
285         }
286     }
287
288     @Override
289     public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
290             final DataNodeContainer container) {
291         final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
292         if (container instanceof AugmentationTarget) {
293             final BindingRuntimeTypes types = getTypes();
294             for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
295                 // Augmentation must have child nodes if is to be used with Binding classes
296                 AugmentationSchemaNode augOrig = augment;
297                 while (augOrig.getOriginalDefinition().isPresent()) {
298                     augOrig = augOrig.getOriginalDefinition().get();
299                 }
300
301                 if (!augment.getChildNodes().isEmpty()) {
302                     final Optional<Type> augType = types.findType(augOrig);
303                     if (augType.isPresent()) {
304                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
305                     }
306                 }
307             }
308         }
309
310         return ImmutableMap.copyOf(identifierToType);
311     }
312
313     @Override
314     public final Class<?> getIdentityClass(final QName input) {
315         return identityClasses.getUnchecked(input);
316     }
317
318     @Override
319     public final String toString() {
320         return MoreObjects.toStringHelper(this)
321                 .add("ClassLoadingStrategy", getStrategy())
322                 .add("runtimeTypes", getTypes())
323                 .toString();
324     }
325
326     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
327         // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
328         return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
329             .collect(ImmutableSet.toImmutableSet()));
330     }
331
332     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
333         for (final MethodSignature definition : type.getMethodDefinitions()) {
334             Type childType = definition.getReturnType();
335             if (childType instanceof ParameterizedType) {
336                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
337             }
338             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
339                 collection.add(childType);
340             }
341         }
342         for (final Type parent : type.getImplements()) {
343             if (parent instanceof GeneratedType) {
344                 collectAllContainerTypes((GeneratedType) parent, collection);
345             }
346         }
347         return collection;
348     }
349
350     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
351         @SuppressWarnings("unchecked")
352         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
353         if (original != null) {
354             return original;
355         }
356         return choice;
357     }
358
359     private static @NonNull Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
360             final CaseSchemaNode originalDefinition) {
361         CaseSchemaNode potential = instantiatedChoice.findCase(originalDefinition.getQName()).orElse(null);
362         if (originalDefinition.equals(potential)) {
363             return Optional.of(potential);
364         }
365         if (potential != null) {
366             SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
367             if (originalDefinition.equals(potentialRoot)) {
368                 return Optional.of(potential);
369             }
370         }
371
372         // We try to find case by name, then lookup its root definition
373         // and compare it with original definition
374         // This solves case, if choice was inside grouping
375         // which was used in different module and thus namespaces are
376         // different, but local names are still same.
377         //
378         // Still we need to check equality of definition, because local name is not
379         // sufficient to uniquelly determine equality of cases
380         //
381         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
382             if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
383                 return Optional.of(caze);
384             }
385         }
386         return Optional.empty();
387     }
388 }