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