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