Move BindingSchemaContextUtils.findInstantiatedCase()
[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.base.Preconditions;
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.BiMap;
20 import com.google.common.collect.HashBiMap;
21 import com.google.common.collect.ImmutableMap;
22 import com.google.common.collect.ImmutableSet;
23 import com.google.common.collect.Iterables;
24 import java.util.AbstractMap.SimpleEntry;
25 import java.util.ArrayList;
26 import java.util.Collection;
27 import java.util.HashMap;
28 import java.util.HashSet;
29 import java.util.Iterator;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.Map.Entry;
33 import java.util.Optional;
34 import java.util.ServiceLoader;
35 import java.util.Set;
36 import org.eclipse.jdt.annotation.Nullable;
37 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeGenerator;
38 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeTypes;
39 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
40 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
41 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
42 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
43 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
44 import org.opendaylight.mdsal.binding.model.api.Type;
45 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
46 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
47 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
48 import org.opendaylight.yangtools.concepts.Immutable;
49 import org.opendaylight.yangtools.yang.binding.Action;
50 import org.opendaylight.yangtools.yang.binding.Augmentation;
51 import org.opendaylight.yangtools.yang.common.QName;
52 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
53 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
54 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
56 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
59 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
61 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
62 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
63 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
65 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
66 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
67 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
68 import org.slf4j.Logger;
69 import org.slf4j.LoggerFactory;
70
71 /**
72  * Runtime Context for Java YANG Binding classes
73  *
74  * <p>Runtime Context provides additional insight in Java YANG Binding,
75  * binding classes and underlying YANG schema, it contains
76  * runtime information, which could not be derived from generated
77  * classes alone using {@link org.opendaylight.mdsal.binding.spec.reflect.BindingReflections}.
78  *
79  * <p>Some of this information are for example list of all available
80  * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
81  * choices are augmentable and new choices may be introduced by additional models.
82  *
83  * <p>Same goes for all possible augmentations.
84  */
85 public final class BindingRuntimeContext implements SchemaContextProvider, Immutable {
86
87     private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
88     private static final BindingRuntimeGenerator GENERATOR = ServiceLoader.load(BindingRuntimeGenerator.class)
89             .findFirst()
90             .orElseThrow(() -> new IllegalStateException("No BindingRuntimeGenerator implementation found"));
91
92     private static final char DOT = '.';
93
94     private final BindingRuntimeTypes runtimeTypes;
95     private final ClassLoadingStrategy strategy;
96
97     private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
98         new CacheLoader<QName, Class<?>>() {
99             @Override
100             public Class<?> load(final QName key) {
101                 final Optional<Type> identityType = runtimeTypes.findIdentity(key);
102                 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
103                 try {
104                     return strategy.loadClass(identityType.get());
105                 } catch (final ClassNotFoundException e) {
106                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
107                 }
108             }
109         });
110
111     private BindingRuntimeContext(final BindingRuntimeTypes runtimeTypes, final ClassLoadingStrategy strategy) {
112         this.runtimeTypes = requireNonNull(runtimeTypes);
113         this.strategy = requireNonNull(strategy);
114     }
115
116     /**
117      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
118      *
119      * @param strategy Class loading strategy to retrieve generated Binding classes
120      * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
121      * @return Instance of BindingRuntimeContext for supplied schema context.
122      */
123     public static BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
124         return new BindingRuntimeContext(GENERATOR.generateTypeMapping(ctx), strategy);
125     }
126
127     /**
128      * Returns a class loading strategy associated with this binding runtime context
129      * which is used to load classes.
130      *
131      * @return Class loading strategy.
132      */
133     public ClassLoadingStrategy getStrategy() {
134         return strategy;
135     }
136
137     /**
138      * Returns an stable immutable view of schema context associated with this Binding runtime context.
139      *
140      * @return stable view of schema context
141      */
142     @Override
143     public SchemaContext getSchemaContext() {
144         return runtimeTypes.getSchemaContext();
145     }
146
147     /**
148      * Returns schema of augmentation.
149      *
150      * <p>Returned schema is schema definition from which augmentation class was generated.
151      * This schema is isolated from other augmentations. This means it contains
152      * augmentation definition as was present in original YANG module.
153      *
154      * <p>Children of returned schema does not contain any additional augmentations,
155      * which may be present in runtime for them, thus returned schema is unsuitable
156      * for use for validation of data.
157      *
158      * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
159      * full model for child nodes, you should use method
160      * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
161      * which will return augmentation schema derived from supplied augmentation target
162      * schema.
163      *
164      * @param augClass Augmentation class
165      * @return Schema of augmentation or null if augmentaiton is not known in this context
166      * @throws IllegalArgumentException If supplied class is not an augmentation
167      */
168     public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
169         checkArgument(Augmentation.class.isAssignableFrom(augClass),
170             "Class %s does not represent augmentation", augClass);
171         return runtimeTypes.findAugmentation(referencedType(augClass)).orElse(null);
172     }
173
174     /**
175      * Returns defining {@link DataSchemaNode} for supplied class.
176      *
177      * <p>Returned schema is schema definition from which class was generated.
178      * This schema may be isolated from augmentations, if supplied class
179      * represent node, which was child of grouping or augmentation.
180      *
181      * <p>For getting augmentation schema from augmentation class use
182      * {@link #getAugmentationDefinition(Class)} instead.
183      *
184      * @param cls Class which represents list, container, choice or case.
185      * @return Schema node, from which class was generated.
186      */
187     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
188         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
189             cls);
190         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
191         return (DataSchemaNode) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
192     }
193
194     public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
195         return (ActionDefinition) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
196     }
197
198     public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
199             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
200         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
201         checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
202         /*
203          * FIXME: Validate augmentation schema lookup
204          *
205          * Currently this algorithm, does not verify if instantiated child nodes
206          * are real one derived from augmentation schema. The problem with
207          * full validation is, if user used copy builders, he may use
208          * augmentation which was generated for different place.
209          *
210          * If this augmentations have same definition, we emit same identifier
211          * with data and it is up to underlying user to validate data.
212          *
213          */
214         final Set<QName> childNames = new HashSet<>();
215         final Set<DataSchemaNode> realChilds = new HashSet<>();
216         for (final DataSchemaNode child : origSchema.getChildNodes()) {
217             final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
218             final String childLocalName = child.getQName().getLocalName();
219             if (dataChildQNname == null) {
220                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
221                     if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
222                         realChilds.add(dataSchemaNode);
223                         childNames.add(dataSchemaNode.getQName());
224                     }
225                 }
226             } else {
227                 realChilds.add(dataChildQNname);
228                 childNames.add(child.getQName());
229             }
230         }
231
232         final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
233         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
234         return new SimpleEntry<>(identifier, proxy);
235     }
236
237     /**
238      * Returns resolved case schema for supplied class.
239      *
240      * @param schema Resolved parent choice schema
241      * @param childClass Class representing case.
242      * @return Optionally a resolved case schema,.empty if the choice is not legal in
243      *         the given context.
244      * @throws IllegalArgumentException If supplied class does not represent case.
245      */
246     public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
247         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
248         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
249
250         /* FIXME: Make sure that if there are multiple augmentations of same
251          * named case, with same structure we treat it as equals
252          * this is due property of Binding specification and copy builders
253          * that user may be unaware that he is using incorrect case
254          * which was generated for choice inside grouping.
255          */
256         final Optional<CaseSchemaNode> found = findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
257         return found;
258     }
259
260     /**
261      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
262      * from which supplied class was generated. Returned schema may be augmented with
263      * additional information, which was not available at compile type
264      * (e.g. third party augmentations).
265      *
266      * @param type Binding Class for which schema should be retrieved.
267      * @return Instance of generated type (definition of Java API), along with
268      *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
269      *     which was used to generate supplied class.
270      */
271     public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
272         return getTypeWithSchema(referencedType(type));
273     }
274
275     private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
276         final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
277             () -> new NullPointerException("Failed to find schema for type " + referencedType));
278         final Type definedType = runtimeTypes.findType(schema).orElseThrow(
279             () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
280
281         if (definedType instanceof GeneratedTypeBuilder) {
282             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
283         }
284         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
285         return new SimpleEntry<>((GeneratedType) definedType, schema);
286     }
287
288     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
289         final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
290
291         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
292             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
293             final Optional<Type> optType = runtimeTypes.findType(originalChoice);
294             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
295             final Type choiceType = optType.get();
296
297             for (Type caze : runtimeTypes.findCases(referencedType(choiceType))) {
298                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
299                 final HashSet<Type> caseChildren = new HashSet<>();
300                 if (caze instanceof GeneratedTypeBuilder) {
301                     caze = ((GeneratedTypeBuilder) caze).build();
302                 }
303                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
304                 for (final Type caseChild : caseChildren) {
305                     childToCase.put(caseChild, caseIdentifier);
306                 }
307             }
308         }
309         return ImmutableMap.copyOf(childToCase);
310     }
311
312     /**
313      * Map enum constants: yang - java.
314      *
315      * @param enumClass enum generated class
316      * @return mapped enum constants from yang with their corresponding values in generated binding classes
317      */
318     public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
319         final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
320         return getEnumMapping(typeWithSchema);
321     }
322
323     /**
324      * Map enum constants: yang - java.
325      *
326      * @param enumClassName enum generated class name
327      * @return mapped enum constants from yang with their corresponding values in generated binding classes
328      */
329     public BiMap<String, String> getEnumMapping(final String enumClassName) {
330         return getEnumMapping(findTypeWithSchema(enumClassName));
331     }
332
333     private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
334         final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
335
336         Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
337         final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
338
339         final HashBiMap<String, String> mappedEnums = HashBiMap.create();
340
341         for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
342             mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
343         }
344
345         // TODO cache these maps for future use
346         return mappedEnums;
347     }
348
349     private Entry<GeneratedType, WithStatus> findTypeWithSchema(final String className) {
350         // All we have is a straight FQCN, which we need to split into a hierarchical JavaTypeName. This involves
351         // some amount of guesswork -- we do that by peeling components at the dot and trying out, e.g. given
352         // "foo.bar.baz.Foo.Bar.Baz" we end up trying:
353         // "foo.bar.baz.Foo.Bar" + "Baz"
354         // "foo.bar.baz.Foo" + Bar" + "Baz"
355         // "foo.bar.baz" + Foo" + Bar" + "Baz"
356         //
357         // And see which one sticks. We cannot rely on capital letters, as they can be used in package names, too.
358         // Nested classes are not common, so we should be arriving at the result pretty quickly.
359         final List<String> components = new ArrayList<>();
360         String packageName = className;
361
362         for (int lastDot = packageName.lastIndexOf(DOT); lastDot != -1; lastDot = packageName.lastIndexOf(DOT)) {
363             components.add(packageName.substring(lastDot + 1));
364             packageName = packageName.substring(0, lastDot);
365
366             final Iterator<String> it = components.iterator();
367             JavaTypeName name = JavaTypeName.create(packageName, it.next());
368             while (it.hasNext()) {
369                 name = name.createEnclosed(it.next());
370             }
371
372             final Type type = new ReferencedTypeImpl(name);
373             final Optional<WithStatus> optSchema = runtimeTypes.findSchema(type);
374             if (!optSchema.isPresent()) {
375                 continue;
376             }
377
378             final WithStatus schema = optSchema.get();
379             final Optional<Type> optDefinedType =  runtimeTypes.findType(schema);
380             if (!optDefinedType.isPresent()) {
381                 continue;
382             }
383
384             final Type definedType = optDefinedType.get();
385             if (definedType instanceof GeneratedTypeBuilder) {
386                 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
387             }
388             checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", className);
389             return new SimpleEntry<>((GeneratedType) definedType, schema);
390         }
391
392         throw new IllegalArgumentException("Failed to find type for " + className);
393     }
394
395     public Set<Class<?>> getCases(final Class<?> choice) {
396         final Collection<Type> cazes = runtimeTypes.findCases(referencedType(choice));
397         final Set<Class<?>> ret = new HashSet<>(cazes.size());
398         for (final Type caze : cazes) {
399             try {
400                 final Class<?> c = strategy.loadClass(caze);
401                 ret.add(c);
402             } catch (final ClassNotFoundException e) {
403                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
404             }
405         }
406         return ret;
407     }
408
409     public Class<?> getClassForSchema(final SchemaNode childSchema) {
410         final SchemaNode origSchema = getOriginalSchema(childSchema);
411         final Optional<Type> clazzType = runtimeTypes.findType(origSchema);
412         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
413             childSchema, origSchema);
414
415         try {
416             return strategy.loadClass(clazzType.get());
417         } catch (final ClassNotFoundException e) {
418             throw new IllegalStateException(e);
419         }
420     }
421
422     public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
423         final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
424         if (container instanceof AugmentationTarget) {
425             for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
426                 // Augmentation must have child nodes if is to be used with Binding classes
427                 AugmentationSchemaNode augOrig = augment;
428                 while (augOrig.getOriginalDefinition().isPresent()) {
429                     augOrig = augOrig.getOriginalDefinition().get();
430                 }
431
432                 if (!augment.getChildNodes().isEmpty()) {
433                     final Optional<Type> augType = runtimeTypes.findType(augOrig);
434                     if (augType.isPresent()) {
435                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
436                     }
437                 }
438             }
439         }
440
441         return ImmutableMap.copyOf(identifierToType);
442     }
443
444     public Class<?> getIdentityClass(final QName input) {
445         return identityClasses.getUnchecked(input);
446     }
447
448     @Override
449     public String toString() {
450         return MoreObjects.toStringHelper(this)
451                 .add("ClassLoadingStrategy", strategy)
452                 .add("runtimeTypes", runtimeTypes)
453                 .toString();
454     }
455
456     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
457         // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
458         return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
459             .collect(ImmutableSet.toImmutableSet()));
460     }
461
462     private static Type referencedType(final Class<?> type) {
463         return new ReferencedTypeImpl(JavaTypeName.create(type));
464     }
465
466     private static Type referencedType(final Type type) {
467         if (type instanceof ReferencedTypeImpl) {
468             return type;
469         }
470         return new ReferencedTypeImpl(type.getIdentifier());
471     }
472
473     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
474         for (final MethodSignature definition : type.getMethodDefinitions()) {
475             Type childType = definition.getReturnType();
476             if (childType instanceof ParameterizedType) {
477                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
478             }
479             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
480                 collection.add(referencedType(childType));
481             }
482         }
483         for (final Type parent : type.getImplements()) {
484             if (parent instanceof GeneratedType) {
485                 collectAllContainerTypes((GeneratedType) parent, collection);
486             }
487         }
488         return collection;
489     }
490
491     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
492         @SuppressWarnings("unchecked")
493         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
494         if (original != null) {
495             return original;
496         }
497         return choice;
498     }
499
500     private static Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
501             final CaseSchemaNode originalDefinition) {
502         CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
503         if (originalDefinition.equals(potential)) {
504             return Optional.of(potential);
505         }
506         if (potential != null) {
507             SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
508             if (originalDefinition.equals(potentialRoot)) {
509                 return Optional.of(potential);
510             }
511         }
512
513         // We try to find case by name, then lookup its root definition
514         // and compare it with original definition
515         // This solves case, if choice was inside grouping
516         // which was used in different module and thus namespaces are
517         // different, but local names are still same.
518         //
519         // Still we need to check equality of definition, because local name is not
520         // sufficient to uniquelly determine equality of cases
521         //
522         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
523             if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
524                 return Optional.of(caze);
525             }
526         }
527         return Optional.empty();
528     }
529 }