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