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