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