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