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