Refactor GeneratedClassLoadingStrategy
[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.MoreObjects;
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.ImmutableSet;
22 import com.google.common.collect.Iterables;
23 import java.util.AbstractMap.SimpleEntry;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.Iterator;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Map.Entry;
32 import java.util.Optional;
33 import java.util.Set;
34 import org.eclipse.jdt.annotation.Nullable;
35 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeTypes;
36 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
37 import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
38 import org.opendaylight.mdsal.binding.generator.impl.BindingSchemaContextUtils;
39 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
40 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
41 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
42 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
43 import org.opendaylight.mdsal.binding.model.api.Type;
44 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
45 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
46 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
47 import org.opendaylight.yangtools.concepts.Immutable;
48 import org.opendaylight.yangtools.yang.binding.Action;
49 import org.opendaylight.yangtools.yang.binding.Augmentation;
50 import org.opendaylight.yangtools.yang.common.QName;
51 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
52 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
53 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
55 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
58 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
59 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
60 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
61 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
62 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
63 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
64 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
65 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
66 import org.slf4j.Logger;
67 import org.slf4j.LoggerFactory;
68
69 /**
70  * Runtime Context for Java YANG Binding classes
71  *
72  * <p>Runtime Context provides additional insight in Java YANG Binding,
73  * binding classes and underlying YANG schema, it contains
74  * runtime information, which could not be derived from generated
75  * classes alone using {@link org.opendaylight.mdsal.binding.spec.reflect.BindingReflections}.
76  *
77  * <p>Some of this information are for example list of all available
78  * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
79  * choices are augmentable and new choices may be introduced by additional models.
80  *
81  * <p>Same goes for all possible augmentations.
82  */
83 public final class BindingRuntimeContext implements Immutable {
84
85     private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
86     private static final char DOT = '.';
87
88     private final BindingRuntimeTypes runtimeTypes;
89     private final ClassLoadingStrategy strategy;
90     private final SchemaContext schemaContext;
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 Optional<Type> identityType = runtimeTypes.findIdentity(key);
97                 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
98                 try {
99                     return strategy.loadClass(identityType.get());
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         runtimeTypes = new BindingGeneratorImpl().generateTypeMapping(schema);
110     }
111
112     /**
113      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
114      *
115      * @param strategy Class loading strategy to retrieve generated Binding classes
116      * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
117      * @return Instance of BindingRuntimeContext for supplied schema context.
118      */
119     public static BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
120         return new BindingRuntimeContext(strategy, ctx);
121     }
122
123     /**
124      * Returns a class loading strategy associated with this binding runtime context
125      * which is used to load classes.
126      *
127      * @return Class loading strategy.
128      */
129     public ClassLoadingStrategy getStrategy() {
130         return strategy;
131     }
132
133     /**
134      * Returns an stable immutable view of schema context associated with this Binding runtime context.
135      *
136      * @return stable view of schema context
137      */
138     public SchemaContext getSchemaContext() {
139         return schemaContext;
140     }
141
142     /**
143      * Returns schema of augmentation.
144      *
145      * <p>Returned schema is schema definition from which augmentation class was generated.
146      * This schema is isolated from other augmentations. This means it contains
147      * augmentation definition as was present in original YANG module.
148      *
149      * <p>Children of returned schema does not contain any additional augmentations,
150      * which may be present in runtime for them, thus returned schema is unsuitable
151      * for use for validation of data.
152      *
153      * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
154      * full model for child nodes, you should use method
155      * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
156      * which will return augmentation schema derived from supplied augmentation target
157      * schema.
158      *
159      * @param augClass Augmentation class
160      * @return Schema of augmentation or null if augmentaiton is not known in this context
161      * @throws IllegalArgumentException If supplied class is not an augmentation
162      */
163     public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
164         checkArgument(Augmentation.class.isAssignableFrom(augClass),
165             "Class %s does not represent augmentation", augClass);
166         return runtimeTypes.findAugmentation(referencedType(augClass)).orElse(null);
167     }
168
169     /**
170      * Returns defining {@link DataSchemaNode} for supplied class.
171      *
172      * <p>Returned schema is schema definition from which class was generated.
173      * This schema may be isolated from augmentations, if supplied class
174      * represent node, which was child of grouping or augmentation.
175      *
176      * <p>For getting augmentation schema from augmentation class use
177      * {@link #getAugmentationDefinition(Class)} instead.
178      *
179      * @param cls Class which represents list, container, choice or case.
180      * @return Schema node, from which class was generated.
181      */
182     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
183         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
184             cls);
185         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
186         return (DataSchemaNode) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
187     }
188
189     public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
190         return (ActionDefinition) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
191     }
192
193     public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
194             final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
195         final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
196         checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
197         /*
198          * FIXME: Validate augmentation schema lookup
199          *
200          * Currently this algorithm, does not verify if instantiated child nodes
201          * are real one derived from augmentation schema. The problem with
202          * full validation is, if user used copy builders, he may use
203          * augmentation which was generated for different place.
204          *
205          * If this augmentations have same definition, we emit same identifier
206          * with data and it is up to underlying user to validate data.
207          *
208          */
209         final Set<QName> childNames = new HashSet<>();
210         final Set<DataSchemaNode> realChilds = new HashSet<>();
211         for (final DataSchemaNode child : origSchema.getChildNodes()) {
212             final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
213             final String childLocalName = child.getQName().getLocalName();
214             if (dataChildQNname == null) {
215                 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
216                     if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
217                         realChilds.add(dataSchemaNode);
218                         childNames.add(dataSchemaNode.getQName());
219                     }
220                 }
221             } else {
222                 realChilds.add(dataChildQNname);
223                 childNames.add(child.getQName());
224             }
225         }
226
227         final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
228         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
229         return new SimpleEntry<>(identifier, proxy);
230     }
231
232     /**
233      * Returns resolved case schema for supplied class.
234      *
235      * @param schema Resolved parent choice schema
236      * @param childClass Class representing case.
237      * @return Optionally a resolved case schema,.empty if the choice is not legal in
238      *         the given context.
239      * @throws IllegalArgumentException If supplied class does not represent case.
240      */
241     public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
242         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
243         checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
244
245         /* FIXME: Make sure that if there are multiple augmentations of same
246          * named case, with same structure we treat it as equals
247          * this is due property of Binding specification and copy builders
248          * that user may be unaware that he is using incorrect case
249          * which was generated for choice inside grouping.
250          */
251         final Optional<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
252                 (CaseSchemaNode) origSchema);
253         return found;
254     }
255
256     /**
257      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
258      * from which supplied class was generated. Returned schema may be augmented with
259      * additional information, which was not available at compile type
260      * (e.g. third party augmentations).
261      *
262      * @param type Binding Class for which schema should be retrieved.
263      * @return Instance of generated type (definition of Java API), along with
264      *     {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
265      *     which was used to generate supplied class.
266      */
267     public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
268         return getTypeWithSchema(referencedType(type));
269     }
270
271     private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
272         final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
273             () -> new NullPointerException("Failed to find schema for type " + referencedType));
274         final Type definedType = runtimeTypes.findType(schema).orElseThrow(
275             () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
276
277         if (definedType instanceof GeneratedTypeBuilder) {
278             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
279         }
280         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
281         return new SimpleEntry<>((GeneratedType) definedType, schema);
282     }
283
284     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
285         final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
286
287         for (final ChoiceSchemaNode choice :  Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
288             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
289             final Optional<Type> optType = runtimeTypes.findType(originalChoice);
290             checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
291             final Type choiceType = optType.get();
292
293             for (Type caze : runtimeTypes.findCases(referencedType(choiceType))) {
294                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
295                 final HashSet<Type> caseChildren = new HashSet<>();
296                 if (caze instanceof GeneratedTypeBuilder) {
297                     caze = ((GeneratedTypeBuilder) caze).build();
298                 }
299                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
300                 for (final Type caseChild : caseChildren) {
301                     childToCase.put(caseChild, caseIdentifier);
302                 }
303             }
304         }
305         return ImmutableMap.copyOf(childToCase);
306     }
307
308     /**
309      * Map enum constants: yang - java.
310      *
311      * @param enumClass enum generated class
312      * @return mapped enum constants from yang with their corresponding values in generated binding classes
313      */
314     public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
315         final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
316         return getEnumMapping(typeWithSchema);
317     }
318
319     /**
320      * Map enum constants: yang - java.
321      *
322      * @param enumClassName enum generated class name
323      * @return mapped enum constants from yang with their corresponding values in generated binding classes
324      */
325     public BiMap<String, String> getEnumMapping(final String enumClassName) {
326         return getEnumMapping(findTypeWithSchema(enumClassName));
327     }
328
329     private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
330         final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
331
332         Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
333         final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
334
335         final HashBiMap<String, String> mappedEnums = HashBiMap.create();
336
337         for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
338             mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
339         }
340
341         // TODO cache these maps for future use
342         return mappedEnums;
343     }
344
345     private Entry<GeneratedType, WithStatus> findTypeWithSchema(final String className) {
346         // All we have is a straight FQCN, which we need to split into a hierarchical JavaTypeName. This involves
347         // some amount of guesswork -- we do that by peeling components at the dot and trying out, e.g. given
348         // "foo.bar.baz.Foo.Bar.Baz" we end up trying:
349         // "foo.bar.baz.Foo.Bar" + "Baz"
350         // "foo.bar.baz.Foo" + Bar" + "Baz"
351         // "foo.bar.baz" + Foo" + Bar" + "Baz"
352         //
353         // And see which one sticks. We cannot rely on capital letters, as they can be used in package names, too.
354         // Nested classes are not common, so we should be arriving at the result pretty quickly.
355         final List<String> components = new ArrayList<>();
356         String packageName = className;
357
358         for (int lastDot = packageName.lastIndexOf(DOT); lastDot != -1; lastDot = packageName.lastIndexOf(DOT)) {
359             components.add(packageName.substring(lastDot + 1));
360             packageName = packageName.substring(0, lastDot);
361
362             final Iterator<String> it = components.iterator();
363             JavaTypeName name = JavaTypeName.create(packageName, it.next());
364             while (it.hasNext()) {
365                 name = name.createEnclosed(it.next());
366             }
367
368             final Type type = new ReferencedTypeImpl(name);
369             final Optional<WithStatus> optSchema = runtimeTypes.findSchema(type);
370             if (!optSchema.isPresent()) {
371                 continue;
372             }
373
374             final WithStatus schema = optSchema.get();
375             final Optional<Type> optDefinedType =  runtimeTypes.findType(schema);
376             if (!optDefinedType.isPresent()) {
377                 continue;
378             }
379
380             final Type definedType = optDefinedType.get();
381             if (definedType instanceof GeneratedTypeBuilder) {
382                 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
383             }
384             checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", className);
385             return new SimpleEntry<>((GeneratedType) definedType, schema);
386         }
387
388         throw new IllegalArgumentException("Failed to find type for " + className);
389     }
390
391     public Set<Class<?>> getCases(final Class<?> choice) {
392         final Collection<Type> cazes = runtimeTypes.findCases(referencedType(choice));
393         final Set<Class<?>> ret = new HashSet<>(cazes.size());
394         for (final Type caze : cazes) {
395             try {
396                 final Class<?> c = strategy.loadClass(caze);
397                 ret.add(c);
398             } catch (final ClassNotFoundException e) {
399                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
400             }
401         }
402         return ret;
403     }
404
405     public Class<?> getClassForSchema(final SchemaNode childSchema) {
406         final SchemaNode origSchema = getOriginalSchema(childSchema);
407         final Optional<Type> clazzType = runtimeTypes.findType(origSchema);
408         checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
409             childSchema, origSchema);
410
411         try {
412             return strategy.loadClass(clazzType.get());
413         } catch (final ClassNotFoundException e) {
414             throw new IllegalStateException(e);
415         }
416     }
417
418     public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
419         final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
420         if (container instanceof AugmentationTarget) {
421             final Set<AugmentationSchemaNode> augments = ((AugmentationTarget) container).getAvailableAugmentations();
422             for (final AugmentationSchemaNode augment : augments) {
423                 // Augmentation must have child nodes if is to be used with Binding classes
424                 AugmentationSchemaNode augOrig = augment;
425                 while (augOrig.getOriginalDefinition().isPresent()) {
426                     augOrig = augOrig.getOriginalDefinition().get();
427                 }
428
429                 if (!augment.getChildNodes().isEmpty()) {
430                     final Optional<Type> augType = runtimeTypes.findType(augOrig);
431                     if (augType.isPresent()) {
432                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
433                     }
434                 }
435             }
436         }
437
438         return ImmutableMap.copyOf(identifierToType);
439     }
440
441     private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
442         // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
443         return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
444             .collect(ImmutableSet.toImmutableSet()));
445     }
446
447     private static Type referencedType(final Class<?> type) {
448         return new ReferencedTypeImpl(JavaTypeName.create(type));
449     }
450
451     private static Type referencedType(final Type type) {
452         if (type instanceof ReferencedTypeImpl) {
453             return type;
454         }
455         return new ReferencedTypeImpl(type.getIdentifier());
456     }
457
458     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
459         for (final MethodSignature definition : type.getMethodDefinitions()) {
460             Type childType = definition.getReturnType();
461             if (childType instanceof ParameterizedType) {
462                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
463             }
464             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
465                 collection.add(referencedType(childType));
466             }
467         }
468         for (final Type parent : type.getImplements()) {
469             if (parent instanceof GeneratedType) {
470                 collectAllContainerTypes((GeneratedType) parent, collection);
471             }
472         }
473         return collection;
474     }
475
476     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
477         @SuppressWarnings("unchecked")
478         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
479         if (original != null) {
480             return original;
481         }
482         return choice;
483     }
484
485     public Class<?> getIdentityClass(final QName input) {
486         return identityClasses.getUnchecked(input);
487     }
488
489     @Override
490     public String toString() {
491         return MoreObjects.toStringHelper(this)
492                 .add("ClassLoadingStrategy", strategy)
493                 .add("runtimeTypes", runtimeTypes)
494                 .add("schemaContext", schemaContext).toString();
495     }
496 }