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