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