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