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