cd05f552afd957d88c691e7bae2358220f147fac
[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.Augmentation;
46 import org.opendaylight.yangtools.yang.binding.BindingMapping;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
49 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
51 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
54 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
61 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
64
65 /**
66  *
67  * Runtime Context for Java YANG Binding classes
68  *
69  *<p>
70  * 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.yangtools.yang.binding.util.BindingReflections}.
74  * <p>
75  * 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  * <p>
79  * Same goes for all possible augmentations.
80  *
81  */
82 public class BindingRuntimeContext implements Immutable {
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      *
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 final 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      * <p>
144      * 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      * <p>
148      * 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      * <p>
152      * For retrieving {@link AugmentationSchemaNode}, which will contains
153      * full model for child nodes, you should use method {@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>
171      * 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      * <p>
175      * 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 augmentation (%s is)",
183             cls);
184         return (DataSchemaNode) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
185     }
186
187     public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
188             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
189         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
190         checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
191         /*
192          * FIXME: Validate augmentation schema lookup
193          *
194          * Currently this algorithm, does not verify if instantiated child nodes
195          * are real one derived from augmentation schema. The problem with
196          * full validation is, if user used copy builders, he may use
197          * augmentation which was generated for different place.
198          *
199          * If this augmentations have same definition, we emit same identifier
200          * with data and it is up to underlying user to validate data.
201          *
202          */
203         final Set<QName> childNames = new HashSet<>();
204         final Set<DataSchemaNode> realChilds = new HashSet<>();
205         for (final DataSchemaNode child : origSchema.getChildNodes()) {
206             final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
207             final String childLocalName = child.getQName().getLocalName();
208             if (dataChildQNname == null) {
209                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
210                     if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
211                         realChilds.add(dataSchemaNode);
212                         childNames.add(dataSchemaNode.getQName());
213                     }
214                 }
215             } else {
216                 realChilds.add(dataChildQNname);
217                 childNames.add(child.getQName());
218             }
219         }
220
221         final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
222         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
223         return new SimpleEntry<>(identifier, proxy);
224     }
225
226     /**
227      *
228      * Returns resolved case schema for supplied class
229      *
230      * @param schema Resolved parent choice schema
231      * @param childClass Class representing case.
232      * @return Optionally a resolved case schema, absent if the choice is not legal in
233      *         the given context.
234      * @throws IllegalArgumentException If supplied class does not represent case.
235      */
236     public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
237         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
238         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
239
240         /* FIXME: Make sure that if there are multiple augmentations of same
241          * named case, with same structure we treat it as equals
242          * this is due property of Binding specification and copy builders
243          * that user may be unaware that he is using incorrect case
244          * which was generated for choice inside grouping.
245          */
246         final Optional<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
247                 (CaseSchemaNode) origSchema);
248         return found;
249     }
250
251     private static Type referencedType(final Class<?> type) {
252         return new ReferencedTypeImpl(JavaTypeName.create(type));
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 Entry<GeneratedType, WithStatus> findTypeWithSchema(final String className) {
329         // All we have is a straight FQCN, which we need to split into a hierarchical JavaTypeName. This involves
330         // some amount of guesswork -- we do that by peeling components at the dot and trying out, e.g. given
331         // "foo.bar.baz.Foo.Bar.Baz" we end up trying:
332         // "foo.bar.baz.Foo.Bar" + "Baz"
333         // "foo.bar.baz.Foo" + Bar" + "Baz"
334         // "foo.bar.baz" + Foo" + Bar" + "Baz"
335         //
336         // And see which one sticks. We cannot rely on capital letters, as they can be used in package names, too.
337         // Nested classes are not common, so we should be arriving at the result pretty quickly.
338         final List<String> components = new ArrayList<>();
339         String packageName = className;
340
341         for (int lastDot = packageName.lastIndexOf(DOT); lastDot != -1; lastDot = packageName.lastIndexOf(DOT)) {
342             components.add(packageName.substring(lastDot + 1));
343             packageName = packageName.substring(0, lastDot);
344
345             final Iterator<String> it = components.iterator();
346             JavaTypeName name = JavaTypeName.create(packageName, it.next());
347             while (it.hasNext()) {
348                 name = name.createEnclosed(it.next());
349             }
350
351             final Type type = new ReferencedTypeImpl(name);
352             final java.util.Optional<WithStatus> optSchema = runtimeTypes.findSchema(type);
353             if (!optSchema.isPresent()) {
354                 continue;
355             }
356
357             final WithStatus schema = optSchema.get();
358             final java.util.Optional<Type> optDefinedType =  runtimeTypes.findType(schema);
359             if (!optDefinedType.isPresent()) {
360                 continue;
361             }
362
363             final Type definedType = optDefinedType.get();
364             if (definedType instanceof GeneratedTypeBuilder) {
365                 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
366             }
367             checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", className);
368             return new SimpleEntry<>((GeneratedType) definedType, schema);
369         }
370
371         throw new IllegalArgumentException("Failed to find type for " + className);
372     }
373
374     private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
375         final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
376
377         Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
378         final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
379
380         final HashBiMap<String, String> mappedEnums = HashBiMap.create();
381
382         for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
383             mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
384         }
385
386         // TODO cache these maps for future use
387         return mappedEnums;
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 Type type) {
449         if (type instanceof ReferencedTypeImpl) {
450             return type;
451         }
452         return new ReferencedTypeImpl(type.getIdentifier());
453     }
454
455     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
456         for (final MethodSignature definition : type.getMethodDefinitions()) {
457             Type childType = definition.getReturnType();
458             if (childType instanceof ParameterizedType) {
459                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
460             }
461             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
462                 collection.add(referencedType(childType));
463             }
464         }
465         for (final Type parent : type.getImplements()) {
466             if (parent instanceof GeneratedType) {
467                 collectAllContainerTypes((GeneratedType) parent, collection);
468             }
469         }
470         return collection;
471     }
472
473     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
474         @SuppressWarnings("unchecked")
475         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
476         if (original != null) {
477             return original;
478         }
479         return choice;
480     }
481
482     public Class<?> getIdentityClass(final QName input) {
483         return identityClasses.getUnchecked(input);
484     }
485 }