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