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