BUG-1513: introduce ChoiceSchemaNode
[mdsal.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / 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.yangtools.sal.binding.generator.util;
9
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.cache.CacheBuilder;
13 import com.google.common.cache.CacheLoader;
14 import com.google.common.cache.LoadingCache;
15 import com.google.common.collect.BiMap;
16 import com.google.common.collect.FluentIterable;
17 import com.google.common.collect.HashBiMap;
18 import com.google.common.collect.HashMultimap;
19 import com.google.common.collect.ImmutableMap;
20 import com.google.common.collect.Multimap;
21 import java.util.AbstractMap;
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 org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
32 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
33 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingSchemaContextUtils;
34 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
35 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
36 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature;
37 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
38 import org.opendaylight.yangtools.sal.binding.model.api.Type;
39 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
43 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
54 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
57 /**
58  *
59  * Runtime Context for Java YANG Binding classes
60  *
61  *<p>
62  * Runtime Context provides additional insight in Java YANG Binding,
63  * binding classes and underlying YANG schema, it contains
64  * runtime information, which could not be derived from generated
65  * classes alone using {@link org.opendaylight.yangtools.yang.binding.util.BindingReflections}.
66  * <p>
67  * Some of this information are for example list of all available
68  * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
69  * choices are augmentable and new choices may be introduced by additional models.
70  * <p>
71  * Same goes for all possible augmentations.
72  *
73  */
74 public class BindingRuntimeContext implements Immutable {
75     private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
76     private final ClassLoadingStrategy strategy;
77     private final SchemaContext schemaContext;
78
79     private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
80     private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
81     private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
82     private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
83     private final Map<QName, Type> identities = new HashMap<>();
84
85     private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
86         new CacheLoader<QName, Class<?>>() {
87             @Override
88             public Class<?> load(final QName key) {
89                 final Type identityType = identities.get(key);
90                 Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
91                 try {
92                     return strategy.loadClass(identityType);
93                 } catch (final ClassNotFoundException e) {
94                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
95                 }
96             }
97         });
98
99     private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
100         this.strategy = strategy;
101         this.schemaContext = schema;
102
103         final BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
104         generator.generateTypes(schema);
105         final Map<Module, ModuleContext> modules = generator.getModuleContexts();
106
107         for (final ModuleContext ctx : modules.values()) {
108             augmentationToSchema.putAll(ctx.getTypeToAugmentation());
109             typeToDefiningSchema.putAll(ctx.getTypeToSchema());
110
111             ctx.getTypedefs();
112             augmentableToAugmentations.putAll(ctx.getAugmentableToAugmentations());
113             choiceToCases.putAll(ctx.getChoiceToCases());
114             identities.putAll(ctx.getIdentities());
115         }
116     }
117
118     /**
119      *
120      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
121      *
122      * @param strategy Class loading strategy to retrieve generated Binding classes
123      * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
124      * @return Instance of BindingRuntimeContext for supplied schema context.
125      */
126     public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
127         return new BindingRuntimeContext(strategy, ctx);
128     }
129
130     /**
131      * Returns a class loading strategy associated with this binding runtime context
132      * which is used to load classes.
133      *
134      * @return Class loading strategy.
135      */
136     public ClassLoadingStrategy getStrategy() {
137         return strategy;
138     }
139
140     /**
141      * Returns an stable immutable view of schema context associated with this Binding runtime context.
142      *
143      * @return stable view of schema context
144      */
145     public SchemaContext getSchemaContext() {
146         return schemaContext;
147     }
148
149     /**
150      * Returns schema of augmentation
151      * <p>
152      * Returned schema is schema definition from which augmentation class was generated.
153      * This schema is isolated from other augmentations. This means it contains
154      * augmentation definition as was present in original YANG module.
155      * <p>
156      * Children of returned schema does not contain any additional augmentations,
157      * which may be present in runtime for them, thus returned schema is unsuitable
158      * for use for validation of data.
159      * <p>
160      * For retrieving {@link AugmentationSchema}, which will contains
161      * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
162      * which will return augmentation schema derived from supplied augmentation target
163      * schema.
164      *
165      * @param augClass Augmentation class
166      * @return Schema of augmentation
167      * @throws IllegalArgumentException If supplied class is not an augmentation or current context does not contain schema for augmentation.
168      */
169     public AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
170         Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
171         final AugmentationSchema ret = augmentationToSchema.get(referencedType(augClass));
172         Preconditions.checkArgument(ret != null, "Supplied augmentation %s is not valid in current context", augClass);
173         return ret;
174     }
175
176     /**
177      * Returns defining {@link DataSchemaNode} for supplied class.
178      *
179      * <p>
180      * Returned schema is schema definition from which class was generated.
181      * This schema may be isolated from augmentations, if supplied class
182      * represent node, which was child of grouping or augmentation.
183      * <p>
184      * For getting augmentation schema from augmentation class use
185      * {@link #getAugmentationDefinition(Class)} instead.
186      *
187      * @param cls Class which represents list, container, choice or case.
188      * @return Schema node, from which class was generated.
189      */
190     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
191         Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
192         return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
193     }
194
195     public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
196             final Class<? extends Augmentation<?>> aug) {
197         final AugmentationSchema origSchema = getAugmentationDefinition(aug);
198         /*
199          * FIXME: Validate augmentation schema lookup
200          *
201          * Currently this algorithm, does not verify if instantiated child nodes
202          * are real one derived from augmentation schema. The problem with
203          * full validation is, if user used copy builders, he may use
204          * augmentation which was generated for different place.
205          *
206          * If this augmentations have same definition, we emit same identifier
207          * with data and it is up to underlying user to validate data.
208          *
209          */
210         final Set<QName> childNames = new HashSet<>();
211         final Set<DataSchemaNode> realChilds = new HashSet<>();
212         for (final DataSchemaNode child : origSchema.getChildNodes()) {
213             realChilds.add(target.getDataChildByName(child.getQName()));
214             childNames.add(child.getQName());
215         }
216
217         final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
218         final AugmentationSchema proxy = new AugmentationSchemaProxy(origSchema, realChilds);
219         return new AbstractMap.SimpleEntry<>(identifier, proxy);
220     }
221
222     /**
223      *
224      * Returns resolved case schema for supplied class
225      *
226      * @param schema Resolved parent choice schema
227      * @param childClass Class representing case.
228      * @return Optionally a resolved case schema, absent if the choice is not legal in
229      *         the given context.
230      * @throws IllegalArgumentException If supplied class does not represent case.
231      */
232     public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
233         final DataSchemaNode origSchema = getSchemaDefinition(childClass);
234         Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
235
236         /* FIXME: Make sure that if there are multiple augmentations of same
237          * named case, with same structure we treat it as equals
238          * this is due property of Binding specification and copy builders
239          * that user may be unaware that he is using incorrect case
240          * which was generated for choice inside grouping.
241          */
242         final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
243                 (ChoiceCaseNode) origSchema);
244         return found;
245     }
246
247     private static Type referencedType(final Class<?> type) {
248         return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
249     }
250
251     /**
252      * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
253      * from which supplied class was generated. Returned schema may be augmented with
254      * additional information, which was not available at compile type
255      * (e.g. third party augmentations).
256      *
257      * @param type Binding Class for which schema should be retrieved.
258      * @return Instance of generated type (definition of Java API), along with
259      *     {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
260      *     which was used to generate supplied class.
261      */
262     public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
263         final Object schema = typeToDefiningSchema.get(referencedType(type));
264         final Type definedType = typeToDefiningSchema.inverse().get(schema);
265         Preconditions.checkNotNull(schema);
266         Preconditions.checkNotNull(definedType);
267         if(definedType instanceof GeneratedTypeBuilder) {
268             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
269         }
270         Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType",type);
271         return new SimpleEntry<>((GeneratedType) definedType,schema);
272
273     }
274
275     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
276         final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();;
277         for (final ChoiceSchemaNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
278             final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
279             final Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
280             final Collection<Type> cases = choiceToCases.get(choiceType);
281
282             for (Type caze : cases) {
283                 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
284                 final HashSet<Type> caseChildren = new HashSet<>();
285                 if (caze instanceof GeneratedTypeBuilder) {
286                     caze = ((GeneratedTypeBuilder) caze).toInstance();
287                 }
288                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
289                 for (final Type caseChild : caseChildren) {
290                     childToCase.put(caseChild, caseIdentifier);
291                 }
292             }
293         }
294         return ImmutableMap.copyOf(childToCase);
295     }
296
297     public Set<Class<?>> getCases(final Class<?> choice) {
298         final Collection<Type> cazes = choiceToCases.get(referencedType(choice));
299         final Set<Class<?>> ret = new HashSet<>(cazes.size());
300         for(final Type caze : cazes) {
301             try {
302                 final Class<?> c = strategy.loadClass(caze);
303                 ret.add(c);
304             } catch (final ClassNotFoundException e) {
305                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
306             }
307         }
308         return ret;
309     }
310
311     public Class<?> getClassForSchema(final SchemaNode childSchema) {
312         final SchemaNode origSchema = getOriginalSchema(childSchema);
313         final Type clazzType = typeToDefiningSchema.inverse().get(origSchema);
314         try {
315             return strategy.loadClass(clazzType);
316         } catch (final ClassNotFoundException e) {
317             throw new IllegalStateException(e);
318         }
319     }
320
321     public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
322         final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
323         if (container instanceof AugmentationTarget) {
324             final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
325             for (final AugmentationSchema augment : augments) {
326                 // Augmentation must have child nodes if is to be used with Binding classes
327                 AugmentationSchema augOrig = augment;
328                 while (augOrig.getOriginalDefinition().isPresent()) {
329                     augOrig = augOrig.getOriginalDefinition().get();
330                 }
331
332                 if (!augment.getChildNodes().isEmpty()) {
333                     final Type augType = typeToDefiningSchema.inverse().get(augOrig);
334                     if (augType != null) {
335                         identifierToType.put(getAugmentationIdentifier(augment),augType);
336                     }
337                 }
338             }
339         }
340
341         return ImmutableMap.copyOf(identifierToType);
342     }
343
344     private AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
345         final Set<QName> childNames = new HashSet<>();
346         for (final DataSchemaNode child : augment.getChildNodes()) {
347             childNames.add(child.getQName());
348         }
349         return new AugmentationIdentifier(childNames);
350     }
351
352     private static Type referencedType(final Type type) {
353         if(type instanceof ReferencedTypeImpl) {
354             return type;
355         }
356         return new ReferencedTypeImpl(type.getPackageName(), type.getName());
357     }
358
359     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
360         for (final MethodSignature definition : type.getMethodDefinitions()) {
361             Type childType = definition.getReturnType();
362             if(childType instanceof ParameterizedType) {
363                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
364             }
365             if(childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
366                 collection.add(referencedType(childType));
367             }
368         }
369         for (final Type parent : type.getImplements()) {
370             if (parent instanceof GeneratedType) {
371                 collectAllContainerTypes((GeneratedType) parent, collection);
372             }
373         }
374         return collection;
375     }
376
377     private static final <T extends SchemaNode> T getOriginalSchema(final T choice) {
378         @SuppressWarnings("unchecked")
379         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
380         if (original != null) {
381             return original;
382         }
383         return choice;
384     }
385
386     public Class<?> getIdentityClass(final QName input) {
387         return identityClasses.getUnchecked(input);
388     }
389 }