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