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