Promote BindingRuntimeContext to binding-generator-api
[mdsal.git] / binding / mdsal-binding-generator-api / src / main / java / org / opendaylight / mdsal / binding / generator / api / BindingRuntimeContext.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.generator.api;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static java.util.Objects.requireNonNull;
13
14 import com.google.common.annotations.Beta;
15 import com.google.common.base.MoreObjects;
16 import com.google.common.cache.CacheBuilder;
17 import com.google.common.cache.CacheLoader;
18 import com.google.common.cache.LoadingCache;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.ImmutableSet;
21 import com.google.common.collect.Iterables;
22 import java.util.AbstractMap.SimpleEntry;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
26 import java.util.Map;
27 import java.util.Map.Entry;
28 import java.util.Optional;
29 import java.util.Set;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.eclipse.jdt.annotation.Nullable;
32 import org.opendaylight.mdsal.binding.model.api.DefaultType;
33 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
34 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
35 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
36 import org.opendaylight.mdsal.binding.model.api.Type;
37 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
38 import org.opendaylight.yangtools.concepts.Immutable;
39 import org.opendaylight.yangtools.yang.binding.Action;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
43 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
46 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
55 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
56 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
59
60 /**
61  * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
62  * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
63  *
64  * <p>Some of this information are for example list of all available children for cases
65  * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
66  * by additional models. Same goes for all possible augmentations.
67  */
68 @Beta
69 public final class BindingRuntimeContext implements SchemaContextProvider, Immutable {
70     private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
71
72     private final @NonNull BindingRuntimeTypes runtimeTypes;
73     private final @NonNull ClassLoadingStrategy strategy;
74
75     private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
76         new CacheLoader<QName, Class<?>>() {
77             @Override
78             public Class<?> load(final QName key) {
79                 final Optional<Type> identityType = runtimeTypes.findIdentity(key);
80                 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
81                 try {
82                     return strategy.loadClass(identityType.get());
83                 } catch (final ClassNotFoundException e) {
84                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
85                 }
86             }
87         });
88
89     private BindingRuntimeContext(final BindingRuntimeTypes runtimeTypes, final ClassLoadingStrategy strategy) {
90         this.runtimeTypes = requireNonNull(runtimeTypes);
91         this.strategy = requireNonNull(strategy);
92     }
93
94     /**
95      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
96      *
97      * @param strategy Class loading strategy to retrieve generated Binding classes
98      * @param runtimeTypes Binding classes to YANG schema mapping
99      * @return A new instance
100      */
101     public static @NonNull BindingRuntimeContext create(final BindingRuntimeTypes runtimeTypes,
102             final ClassLoadingStrategy strategy) {
103         return new BindingRuntimeContext(runtimeTypes, strategy);
104     }
105
106     /**
107      * Returns a class loading strategy associated with this binding runtime context
108      * which is used to load classes.
109      *
110      * @return Class loading strategy.
111      */
112     public @NonNull ClassLoadingStrategy getStrategy() {
113         return strategy;
114     }
115
116     /**
117      * Returns an stable immutable view of schema context associated with this Binding runtime context.
118      *
119      * @return stable view of schema context
120      */
121     @Override
122     public SchemaContext getSchemaContext() {
123         return runtimeTypes.getSchemaContext();
124     }
125
126     /**
127      * Returns schema of augmentation.
128      *
129      * <p>Returned schema is schema definition from which augmentation class was generated.
130      * This schema is isolated from other augmentations. This means it contains
131      * augmentation definition as was present in original YANG module.
132      *
133      * <p>Children of returned schema does not contain any additional augmentations,
134      * which may be present in runtime for them, thus returned schema is unsuitable
135      * for use for validation of data.
136      *
137      * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
138      * full model for child nodes, you should use method
139      * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
140      * which will return augmentation schema derived from supplied augmentation target
141      * schema.
142      *
143      * @param augClass Augmentation class
144      * @return Schema of augmentation or null if augmentaiton is not known in this context
145      * @throws IllegalArgumentException If supplied class is not an augmentation
146      */
147     public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
148         checkArgument(Augmentation.class.isAssignableFrom(augClass),
149             "Class %s does not represent augmentation", augClass);
150         return runtimeTypes.findAugmentation(DefaultType.of(augClass)).orElse(null);
151     }
152
153     /**
154      * Returns defining {@link DataSchemaNode} for supplied class.
155      *
156      * <p>Returned schema is schema definition from which class was generated.
157      * This schema may be isolated from augmentations, if supplied class
158      * represent node, which was child of grouping or augmentation.
159      *
160      * <p>For getting augmentation schema from augmentation class use
161      * {@link #getAugmentationDefinition(Class)} instead.
162      *
163      * @param cls Class which represents list, container, choice or case.
164      * @return Schema node, from which class was generated.
165      */
166     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
167         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
168             cls);
169         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
170         return (DataSchemaNode) runtimeTypes.findSchema(DefaultType.of(cls)).orElse(null);
171     }
172
173     public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
174         return (ActionDefinition) runtimeTypes.findSchema(DefaultType.of(cls)).orElse(null);
175     }
176
177     public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
178             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
179         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
180         checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
181         /*
182          * FIXME: Validate augmentation schema lookup
183          *
184          * Currently this algorithm, does not verify if instantiated child nodes
185          * are real one derived from augmentation schema. The problem with
186          * full validation is, if user used copy builders, he may use
187          * augmentation which was generated for different place.
188          *
189          * If this augmentations have same definition, we emit same identifier
190          * with data and it is up to underlying user to validate data.
191          *
192          */
193         final Set<QName> childNames = new HashSet<>();
194         final Set<DataSchemaNode> realChilds = new HashSet<>();
195         for (final DataSchemaNode child : origSchema.getChildNodes()) {
196             final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
197             final String childLocalName = child.getQName().getLocalName();
198             if (dataChildQNname == null) {
199                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
200                     if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
201                         realChilds.add(dataSchemaNode);
202                         childNames.add(dataSchemaNode.getQName());
203                     }
204                 }
205             } else {
206                 realChilds.add(dataChildQNname);
207                 childNames.add(child.getQName());
208             }
209         }
210
211         final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
212         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
213         return new SimpleEntry<>(identifier, proxy);
214     }
215
216     /**
217      * Returns resolved case schema for supplied class.
218      *
219      * @param schema Resolved parent choice schema
220      * @param childClass Class representing case.
221      * @return Optionally a resolved case schema,.empty if the choice is not legal in
222      *         the given context.
223      * @throws IllegalArgumentException If supplied class does not represent case.
224      */
225     public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
226         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
227         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
228
229         /* FIXME: Make sure that if there are multiple augmentations of same
230          * named case, with same structure we treat it as equals
231          * this is due property of Binding specification and copy builders
232          * that user may be unaware that he is using incorrect case
233          * which was generated for choice inside grouping.
234          */
235         final Optional<CaseSchemaNode> found = findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
236         return found;
237     }
238
239     /**
240      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
241      * from which supplied class was generated. Returned schema may be augmented with
242      * additional information, which was not available at compile type
243      * (e.g. third party augmentations).
244      *
245      * @param type Binding Class for which schema should be retrieved.
246      * @return Instance of generated type (definition of Java API), along with
247      *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
248      *     which was used to generate supplied class.
249      */
250     public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
251         return getTypeWithSchema(DefaultType.of(type));
252     }
253
254     private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
255         final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
256             () -> new NullPointerException("Failed to find schema for type " + referencedType));
257         final Type definedType = runtimeTypes.findType(schema).orElseThrow(
258             () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
259
260         if (definedType instanceof GeneratedTypeBuilder) {
261             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
262         }
263         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
264         return new SimpleEntry<>((GeneratedType) definedType, schema);
265     }
266
267     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
268         final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
269
270         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
271             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
272             final Optional<Type> optType = runtimeTypes.findType(originalChoice);
273             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
274             final Type choiceType = optType.get();
275
276             for (Type caze : runtimeTypes.findCases(choiceType)) {
277                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
278                 final HashSet<Type> caseChildren = new HashSet<>();
279                 if (caze instanceof GeneratedTypeBuilder) {
280                     caze = ((GeneratedTypeBuilder) caze).build();
281                 }
282                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
283                 for (final Type caseChild : caseChildren) {
284                     childToCase.put(caseChild, caseIdentifier);
285                 }
286             }
287         }
288         return ImmutableMap.copyOf(childToCase);
289     }
290
291     public Set<Class<?>> getCases(final Class<?> choice) {
292         final Collection<Type> cazes = runtimeTypes.findCases(DefaultType.of(choice));
293         final Set<Class<?>> ret = new HashSet<>(cazes.size());
294         for (final Type caze : cazes) {
295             try {
296                 final Class<?> c = strategy.loadClass(caze);
297                 ret.add(c);
298             } catch (final ClassNotFoundException e) {
299                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
300             }
301         }
302         return ret;
303     }
304
305     public Class<?> getClassForSchema(final SchemaNode childSchema) {
306         final SchemaNode origSchema = getOriginalSchema(childSchema);
307         final Optional<Type> clazzType = runtimeTypes.findType(origSchema);
308         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
309             childSchema, origSchema);
310
311         try {
312             return strategy.loadClass(clazzType.get());
313         } catch (final ClassNotFoundException e) {
314             throw new IllegalStateException(e);
315         }
316     }
317
318     public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
319         final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
320         if (container instanceof AugmentationTarget) {
321             for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
322                 // Augmentation must have child nodes if is to be used with Binding classes
323                 AugmentationSchemaNode augOrig = augment;
324                 while (augOrig.getOriginalDefinition().isPresent()) {
325                     augOrig = augOrig.getOriginalDefinition().get();
326                 }
327
328                 if (!augment.getChildNodes().isEmpty()) {
329                     final Optional<Type> augType = runtimeTypes.findType(augOrig);
330                     if (augType.isPresent()) {
331                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
332                     }
333                 }
334             }
335         }
336
337         return ImmutableMap.copyOf(identifierToType);
338     }
339
340     public Class<?> getIdentityClass(final QName input) {
341         return identityClasses.getUnchecked(input);
342     }
343
344     @Override
345     public String toString() {
346         return MoreObjects.toStringHelper(this)
347                 .add("ClassLoadingStrategy", strategy)
348                 .add("runtimeTypes", runtimeTypes)
349                 .toString();
350     }
351
352     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
353         // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
354         return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
355             .collect(ImmutableSet.toImmutableSet()));
356     }
357
358     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
359         for (final MethodSignature definition : type.getMethodDefinitions()) {
360             Type childType = definition.getReturnType();
361             if (childType instanceof ParameterizedType) {
362                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
363             }
364             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
365                 collection.add(childType);
366             }
367         }
368         for (final Type parent : type.getImplements()) {
369             if (parent instanceof GeneratedType) {
370                 collectAllContainerTypes((GeneratedType) parent, collection);
371             }
372         }
373         return collection;
374     }
375
376     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
377         @SuppressWarnings("unchecked")
378         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
379         if (original != null) {
380             return original;
381         }
382         return choice;
383     }
384
385     private static Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
386             final CaseSchemaNode originalDefinition) {
387         CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
388         if (originalDefinition.equals(potential)) {
389             return Optional.of(potential);
390         }
391         if (potential != null) {
392             SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
393             if (originalDefinition.equals(potentialRoot)) {
394                 return Optional.of(potential);
395             }
396         }
397
398         // We try to find case by name, then lookup its root definition
399         // and compare it with original definition
400         // This solves case, if choice was inside grouping
401         // which was used in different module and thus namespaces are
402         // different, but local names are still same.
403         //
404         // Still we need to check equality of definition, because local name is not
405         // sufficient to uniquelly determine equality of cases
406         //
407         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
408             if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
409                 return Optional.of(caze);
410             }
411         }
412         return Optional.empty();
413     }
414 }