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