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