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