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