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