bdcd7c719886e464611b7fd98ed0edb6e60c0487
[mdsal.git] / binding / mdsal-binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / 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.yangtools.sal.binding.generator.util;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import com.google.common.collect.BiMap;
16 import com.google.common.collect.FluentIterable;
17 import com.google.common.collect.HashBiMap;
18 import com.google.common.collect.HashMultimap;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Multimap;
21 import java.util.AbstractMap;
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.yangtools.binding.generator.util.ReferencedTypeImpl;
31 import org.opendaylight.yangtools.concepts.Immutable;
32 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
33 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
34 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingSchemaContextUtils;
35 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
36 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
37 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature;
38 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
39 import org.opendaylight.yangtools.sal.binding.model.api.Type;
40 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
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.AugmentationSchema;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
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.Module;
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.ExtendedType;
58 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
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     private final ClassLoadingStrategy strategy;
82     private final SchemaContext schemaContext;
83
84     private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
85     private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
86     private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
87     private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
88     private final Map<QName, Type> identities = new HashMap<>();
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 Type identityType = identities.get(key);
95                 Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
96                 try {
97                     return strategy.loadClass(identityType);
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
108         final BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
109         generator.generateTypes(schema);
110         final Map<Module, ModuleContext> modules = generator.getModuleContexts();
111
112         for (final ModuleContext ctx : modules.values()) {
113             augmentationToSchema.putAll(ctx.getTypeToAugmentation());
114             typeToDefiningSchema.putAll(ctx.getTypeToSchema());
115
116             ctx.getTypedefs();
117             augmentableToAugmentations.putAll(ctx.getAugmentableToAugmentations());
118             choiceToCases.putAll(ctx.getChoiceToCases());
119             identities.putAll(ctx.getIdentities());
120         }
121     }
122
123     /**
124      *
125      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
126      *
127      * @param strategy Class loading strategy to retrieve generated Binding classes
128      * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
129      * @return Instance of BindingRuntimeContext for supplied schema context.
130      */
131     public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
132         return new BindingRuntimeContext(strategy, ctx);
133     }
134
135     /**
136      * Returns a class loading strategy associated with this binding runtime context
137      * which is used to load classes.
138      *
139      * @return Class loading strategy.
140      */
141     public ClassLoadingStrategy getStrategy() {
142         return strategy;
143     }
144
145     /**
146      * Returns an stable immutable view of schema context associated with this Binding runtime context.
147      *
148      * @return stable view of schema context
149      */
150     public SchemaContext getSchemaContext() {
151         return schemaContext;
152     }
153
154     /**
155      * Returns schema of augmentation
156      * <p>
157      * Returned schema is schema definition from which augmentation class was generated.
158      * This schema is isolated from other augmentations. This means it contains
159      * augmentation definition as was present in original YANG module.
160      * <p>
161      * Children of returned schema does not contain any additional augmentations,
162      * which may be present in runtime for them, thus returned schema is unsuitable
163      * for use for validation of data.
164      * <p>
165      * For retrieving {@link AugmentationSchema}, which will contains
166      * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
167      * which will return augmentation schema derived from supplied augmentation target
168      * schema.
169      *
170      * @param augClass Augmentation class
171      * @return Schema of augmentation or null if augmentaiton is not known in this context
172      * @throws IllegalArgumentException If supplied class is not an augmentation
173      */
174     public @Nullable AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
175         Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
176         return augmentationToSchema.get(referencedType(augClass));
177     }
178
179     /**
180      * Returns defining {@link DataSchemaNode} for supplied class.
181      *
182      * <p>
183      * Returned schema is schema definition from which class was generated.
184      * This schema may be isolated from augmentations, if supplied class
185      * represent node, which was child of grouping or augmentation.
186      * <p>
187      * For getting augmentation schema from augmentation class use
188      * {@link #getAugmentationDefinition(Class)} instead.
189      *
190      * @param cls Class which represents list, container, choice or case.
191      * @return Schema node, from which class was generated.
192      */
193     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
194         Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
195         return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
196     }
197
198     public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
199             final Class<? extends Augmentation<?>> aug) {
200         final AugmentationSchema origSchema = getAugmentationDefinition(aug);
201         Preconditions.checkArgument(origSchema != null, "Augmentation %s is not known in current schema context",aug);
202         /*
203          * FIXME: Validate augmentation schema lookup
204          *
205          * Currently this algorithm, does not verify if instantiated child nodes
206          * are real one derived from augmentation schema. The problem with
207          * full validation is, if user used copy builders, he may use
208          * augmentation which was generated for different place.
209          *
210          * If this augmentations have same definition, we emit same identifier
211          * with data and it is up to underlying user to validate data.
212          *
213          */
214         final Set<QName> childNames = new HashSet<>();
215         final Set<DataSchemaNode> realChilds = new HashSet<>();
216         for (final DataSchemaNode child : origSchema.getChildNodes()) {
217             realChilds.add(target.getDataChildByName(child.getQName()));
218             childNames.add(child.getQName());
219         }
220
221         final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
222         final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
223         return new AbstractMap.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<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
237         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
238         Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "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<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
247                 (ChoiceCaseNode) origSchema);
248         return found;
249     }
250
251     private static Type referencedType(final Class<?> type) {
252         return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
253     }
254
255     static Type referencedType(final String type) {
256         final int packageClassSeparator = type.lastIndexOf(DOT);
257         return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), type.substring(packageClassSeparator + 1));
258     }
259
260     /**
261      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
262      * from which supplied class was generated. Returned schema may be augmented with
263      * additional information, which was not available at compile type
264      * (e.g. third party augmentations).
265      *
266      * @param type Binding Class for which schema should be retrieved.
267      * @return Instance of generated type (definition of Java API), along with
268      *     {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
269      *     which was used to generate supplied class.
270      */
271     public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
272         return getTypeWithSchema(referencedType(type));
273     }
274
275     public Entry<GeneratedType, Object> getTypeWithSchema(final String type) {
276         return getTypeWithSchema(referencedType(type));
277     }
278
279     private Entry<GeneratedType, Object> getTypeWithSchema(final Type referencedType) {
280         final Object schema = typeToDefiningSchema.get(referencedType);
281         final Type definedType = typeToDefiningSchema.inverse().get(schema);
282         Preconditions.checkNotNull(schema);
283         Preconditions.checkNotNull(definedType);
284         if(definedType instanceof GeneratedTypeBuilder) {
285             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
286         }
287         Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType", referencedType);
288         return new SimpleEntry<>((GeneratedType) definedType,schema);
289     }
290
291     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
292         final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();
293         for (final ChoiceSchemaNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
294             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
295             final Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
296             final Collection<Type> cases = choiceToCases.get(choiceType);
297
298             for (Type caze : cases) {
299                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
300                 final HashSet<Type> caseChildren = new HashSet<>();
301                 if (caze instanceof GeneratedTypeBuilder) {
302                     caze = ((GeneratedTypeBuilder) caze).toInstance();
303                 }
304                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
305                 for (final Type caseChild : caseChildren) {
306                     childToCase.put(caseChild, caseIdentifier);
307                 }
308             }
309         }
310         return ImmutableMap.copyOf(childToCase);
311     }
312
313     /**
314      * Map enum constants: yang - java
315      *
316      * @param enumClass enum generated class
317      * @return mapped enum constants from yang with their corresponding values in generated binding classes
318      */
319     public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
320         final Map.Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
321         return getEnumMapping(typeWithSchema);
322     }
323
324     /**
325      * See {@link #getEnumMapping(Class)}}
326      */
327     public BiMap<String, String> getEnumMapping(final String enumClass) {
328         final Map.Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
329         return getEnumMapping(typeWithSchema);
330     }
331
332     private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, Object> typeWithSchema) {
333         final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
334
335         final EnumTypeDefinition enumType;
336         if(typeDef instanceof ExtendedType) {
337             enumType = (EnumTypeDefinition) ((ExtendedType) typeDef).getBaseType();
338         } else {
339             Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
340             enumType = (EnumTypeDefinition) typeDef;
341         }
342
343         final HashBiMap<String, String> mappedEnums = HashBiMap.create();
344
345         for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
346             mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
347         }
348
349         // TODO cache these maps for future use
350         return mappedEnums;
351     }
352
353     public Set<Class<?>> getCases(final Class<?> choice) {
354         final Collection<Type> cazes = choiceToCases.get(referencedType(choice));
355         final Set<Class<?>> ret = new HashSet<>(cazes.size());
356         for(final Type caze : cazes) {
357             try {
358                 final Class<?> c = strategy.loadClass(caze);
359                 ret.add(c);
360             } catch (final ClassNotFoundException e) {
361                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
362             }
363         }
364         return ret;
365     }
366
367     public Class<?> getClassForSchema(final SchemaNode childSchema) {
368         final SchemaNode origSchema = getOriginalSchema(childSchema);
369         final Type clazzType = typeToDefiningSchema.inverse().get(origSchema);
370         try {
371             return strategy.loadClass(clazzType);
372         } catch (final ClassNotFoundException e) {
373             throw new IllegalStateException(e);
374         }
375     }
376
377     public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
378         final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
379         if (container instanceof AugmentationTarget) {
380             final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
381             for (final AugmentationSchema augment : augments) {
382                 // Augmentation must have child nodes if is to be used with Binding classes
383                 AugmentationSchema augOrig = augment;
384                 while (augOrig.getOriginalDefinition().isPresent()) {
385                     augOrig = augOrig.getOriginalDefinition().get();
386                 }
387
388                 if (!augment.getChildNodes().isEmpty()) {
389                     final Type augType = typeToDefiningSchema.inverse().get(augOrig);
390                     if (augType != null) {
391                         identifierToType.put(getAugmentationIdentifier(augment),augType);
392                     }
393                 }
394             }
395         }
396
397         return ImmutableMap.copyOf(identifierToType);
398     }
399
400     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
401         final Set<QName> childNames = new HashSet<>();
402         for (final DataSchemaNode child : augment.getChildNodes()) {
403             childNames.add(child.getQName());
404         }
405         return new AugmentationIdentifier(childNames);
406     }
407
408     private static Type referencedType(final Type type) {
409         if(type instanceof ReferencedTypeImpl) {
410             return type;
411         }
412         return new ReferencedTypeImpl(type.getPackageName(), type.getName());
413     }
414
415     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
416         for (final MethodSignature definition : type.getMethodDefinitions()) {
417             Type childType = definition.getReturnType();
418             if(childType instanceof ParameterizedType) {
419                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
420             }
421             if(childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
422                 collection.add(referencedType(childType));
423             }
424         }
425         for (final Type parent : type.getImplements()) {
426             if (parent instanceof GeneratedType) {
427                 collectAllContainerTypes((GeneratedType) parent, collection);
428             }
429         }
430         return collection;
431     }
432
433     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
434         @SuppressWarnings("unchecked")
435         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
436         if (original != null) {
437             return original;
438         }
439         return choice;
440     }
441
442     public Class<?> getIdentityClass(final QName input) {
443         return identityClasses.getUnchecked(input);
444     }
445 }