Merge "Bug 1475: Correctly handle case of typedef that extends boolean"
[mdsal.git] / code-generator / binding-generator-impl / src / main / java / org / opendaylight / yangtools / sal / binding / generator / util / BindingRuntimeContext.java
1 package org.opendaylight.yangtools.sal.binding.generator.util;
2
3 import com.google.common.base.Optional;
4 import com.google.common.base.Preconditions;
5 import com.google.common.collect.BiMap;
6 import com.google.common.collect.FluentIterable;
7 import com.google.common.collect.HashBiMap;
8 import com.google.common.collect.HashMultimap;
9 import com.google.common.collect.ImmutableMap;
10 import com.google.common.collect.Multimap;
11 import java.util.AbstractMap;
12 import java.util.AbstractMap.SimpleEntry;
13 import java.util.Collection;
14 import java.util.HashMap;
15 import java.util.HashSet;
16 import java.util.Map;
17 import java.util.Map.Entry;
18 import java.util.Set;
19 import org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
20 import org.opendaylight.yangtools.concepts.Immutable;
21 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
22 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
23 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingSchemaContextUtils;
24 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
25 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
26 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature;
27 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
28 import org.opendaylight.yangtools.sal.binding.model.api.Type;
29 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
30 import org.opendaylight.yangtools.yang.binding.Augmentation;
31 import org.opendaylight.yangtools.yang.common.QName;
32 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
33 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
34 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
35 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
36 import org.opendaylight.yangtools.yang.model.api.ChoiceNode;
37 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
38 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
39 import org.opendaylight.yangtools.yang.model.api.Module;
40 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
41 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
42 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
43 /**
44  *
45  * Runtime Context for Java YANG Binding classes
46  *
47  *<p>
48  * Runtime Context provides additional insight in Java YANG Binding,
49  * binding classes and underlying YANG schema, it contains
50  * runtime information, which could not be derived from generated
51  * classes alone using {@link org.opendaylight.yangtools.yang.binding.util.BindingReflections}.
52  * <p>
53  * Some of this information are for example list of all available
54  * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
55  * choices are augmentable and new choices may be introduced by additional models.
56  * <p>
57  * Same goes for all possible augmentations.
58  *
59  */
60 public class BindingRuntimeContext implements Immutable {
61
62     private final ClassLoadingStrategy strategy;
63     private final SchemaContext schemaContext;
64
65     private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
66     private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
67     private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
68     private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
69
70     private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
71         this.strategy = strategy;
72         this.schemaContext = schema;
73
74         BindingGeneratorImpl generator = new BindingGeneratorImpl();
75         generator.generateTypes(schema);
76         Map<Module, ModuleContext> modules = generator.getModuleContexts();
77
78         for (Entry<Module, ModuleContext> entry : modules.entrySet()) {
79             ModuleContext ctx = entry.getValue();
80             augmentationToSchema.putAll(ctx.getTypeToAugmentation());
81             typeToDefiningSchema.putAll(ctx.getTypeToSchema());
82             augmentableToAugmentations.putAll(ctx.getAugmentableToAugmentations());
83             choiceToCases.putAll(ctx.getChoiceToCases());
84         }
85     }
86
87     /**
88      *
89      * Creates Binding Runtime Context from supplied class loading strategy and schema context.
90      *
91      * @param strategy Class loading strategy to retrieve generated Binding classes
92      * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
93      * @return Instance of BindingRuntimeContext for supplied schema context.
94      */
95     public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
96
97         return new BindingRuntimeContext(strategy, ctx);
98     }
99
100     /**
101      * Returns a class loading strategy associated with this binding runtime context
102      * which is used to load classes.
103      *
104      * @return Class loading strategy.
105      */
106     public ClassLoadingStrategy getStrategy() {
107         return strategy;
108     }
109
110     /**
111      * Returns an stable immutable view of schema context associated with this Binding runtime context.
112      *
113      * @return stable view of schema context
114      */
115     public SchemaContext getSchemaContext() {
116         return schemaContext;
117     }
118
119     /**
120      * Returns schema of augmentation
121      * <p>
122      * Returned schema is schema definition from which augmentation class was generated.
123      * This schema is isolated from other augmentations. This means it contains
124      * augmentation definition as was present in original YANG module.
125      * <p>
126      * Children of returned schema does not contain any additional augmentations,
127      * which may be present in runtime for them, thus returned schema is unsuitable
128      * for use for validation of data.
129      * <p>
130      * For retrieving {@link AugmentationSchema}, which will contains
131      * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
132      * which will return augmentation schema derived from supplied augmentation target
133      * schema.
134      *
135      * @param augClass Augmentation class
136      * @return Schema of augmentation
137      * @throws IllegalArgumentException If supplied class is not an augmentation or current context does not contain schema for augmenation.
138      */
139     public AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
140         Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass),"Class {} does not represent augmentation",augClass);
141         final AugmentationSchema ret = augmentationToSchema.get(referencedType(augClass));
142         Preconditions.checkArgument(ret != null, "Supplied augmentation {} is not valid in current context",augClass);
143         return ret;
144     }
145
146     /**
147      * Returns defining {@link DataSchemaNode} for supplied class.
148      *
149      * <p>
150      * Returned schema is schema definition from which class was generated.
151      * This schema may be isolated from augmentations, if supplied class
152      * represent node, which was child of grouping or augmentation.
153      * <p>
154      * For getting augmentation schema from augmentation class use
155      * {@link #getAugmentationDefinition(Class)} instead.
156      *
157      * @param cls Class which represents list, container, choice or case.
158      * @return Schema node, from which class was generated.
159      */
160     public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
161         Preconditions.checkArgument(Augmentation.class.isAssignableFrom(cls));
162         return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
163     }
164
165     public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
166             final Class<? extends Augmentation<?>> aug) {
167         AugmentationSchema origSchema = getAugmentationDefinition(aug);
168         /*
169          * FIXME: Validate augmentation schema lookup
170          *
171          * Currently this algorithm, does not verify if instantiated child nodes
172          * are real one derived from augmentation schema. The problem with
173          * full validation is, if user used copy builders, he may use
174          * augmentation which was generated for different place.
175          *
176          * If this augmentations have same definition, we emit same identifier
177          * with data and it is up to underlying user to validate data.
178          *
179          */
180         Set<QName> childNames = new HashSet<>();
181         Set<DataSchemaNode> realChilds = new HashSet<>();
182         for (DataSchemaNode child : origSchema.getChildNodes()) {
183             realChilds.add(target.getDataChildByName(child.getQName()));
184             childNames.add(child.getQName());
185         }
186
187         AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
188         AugmentationSchema proxy = new AugmentationSchemaProxy(origSchema, realChilds);
189         return new AbstractMap.SimpleEntry<>(identifier, proxy);
190     }
191
192     /**
193      *
194      * Returns resolved case schema for supplied class
195      *
196      * @param schema Resolved parent choice schema
197      * @param childClass Class representing case.
198      * @return Resolved case schema.
199      * @throws IllegalArgumentException If supplied class does not represent case or supplied case class is not
200      * valid in the context of parent choice schema.
201      */
202     public ChoiceCaseNode getCaseSchemaDefinition(final ChoiceNode schema, final Class<?> childClass) throws IllegalArgumentException {
203         DataSchemaNode origSchema = getSchemaDefinition(childClass);
204         Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied {} is not case.");
205         /* FIXME: Make sure that if there are multiple augmentations of same
206          * named case, with same structure we treat it as equals
207          * this is due property of Binding specification and copy builders
208          * that user may be unaware that he is using incorrect case
209          * which was generated for choice inside grouping.
210          */
211         Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
212                 (ChoiceCaseNode) origSchema);
213         Preconditions.checkArgument(found.isPresent(), "Supplied {} is not valid case in schema", schema);
214         return found.get();
215     }
216
217     private static Type referencedType(final Class<?> type) {
218         return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
219     }
220
221     public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
222         Object schema = typeToDefiningSchema.get(referencedType(type));
223         Type definedType = typeToDefiningSchema.inverse().get(schema);
224         Preconditions.checkNotNull(schema);
225         Preconditions.checkNotNull(definedType);
226
227         return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
228     }
229
230     public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
231         Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();;
232         for(ChoiceNode choice :  FluentIterable.from(schema.getChildNodes()).filter(ChoiceNode.class)) {
233             ChoiceNode originalChoice = getOriginalSchema(choice);
234             Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
235             Collection<Type> cases = choiceToCases.get(choiceType);
236
237             for(Type caze : cases) {
238                 Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
239                 HashSet<Type> caseChildren = new HashSet<>();
240                 if(caze instanceof GeneratedTypeBuilder) {
241                     caze = ((GeneratedTypeBuilder) caze).toInstance();
242                 }
243                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
244                 for(Type caseChild : caseChildren) {
245                     childToCase.put(caseChild, caseIdentifier);
246                 }
247             }
248         }
249         return ImmutableMap.copyOf(childToCase);
250
251     }
252
253     private static Type referencedType(final Type type) {
254         if(type instanceof ReferencedTypeImpl) {
255             return type;
256         }
257         return new ReferencedTypeImpl(type.getPackageName(), type.getName());
258     }
259
260     private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
261         for (MethodSignature definition : type.getMethodDefinitions()) {
262             Type childType = definition.getReturnType();
263             if(childType instanceof ParameterizedType) {
264                 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
265             }
266             if(childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
267                 collection.add(referencedType(childType));
268             }
269         }
270         for (Type parent : type.getImplements()) {
271             if (parent instanceof GeneratedType) {
272                 collectAllContainerTypes((GeneratedType) parent, collection);
273             }
274         }
275         return collection;
276     }
277
278     private static final <T extends SchemaNode> T getOriginalSchema(final T choice) {
279         @SuppressWarnings("unchecked")
280         T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
281         if(original != null) {
282             return original;
283         }
284         return choice;
285     }
286
287 }