2 * Copyright (c) 2017 Pantheon Technologies s.r.o. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.javav2.runtime.context;
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;
28 import java.util.Map.Entry;
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;
69 * Runtime Context for Java YANG Binding classes
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}.
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.
81 * Same goes for all possible augmentations.
85 public class BindingRuntimeContext implements Immutable {
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;
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<>();
97 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
98 new CacheLoader<QName, Class<?>>() {
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);
104 return BindingRuntimeContext.this.strategy.loadClass(identityType);
105 } catch (final ClassNotFoundException e) {
106 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
111 private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
112 this.strategy = strategy;
113 this.schemaContext = schema;
115 final BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
116 final Map<Module, ModuleContext> modules = generator.getModuleContexts(this.schemaContext);
118 for (final ModuleContext ctx : modules.values()) {
119 this.augmentationToSchema.putAll(ctx.getTypeToAugmentation());
120 this.typeToDefiningSchema.putAll(ctx.getTypeToSchema());
123 this.choiceToCases.putAll(ctx.getChoiceToCases());
124 this.identities.putAll(ctx.getIdentities());
129 * Creates Binding Runtime Context from supplied class loading strategy and
133 * - class loading strategy to retrieve generated Binding classes
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.
139 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
140 return new BindingRuntimeContext(strategy, ctx);
144 * Returns a class loading strategy associated with this binding runtime context
145 * which is used to load classes.
147 * @return Class loading strategy.
149 public ClassLoadingStrategy getStrategy() {
150 return this.strategy;
154 * Returns an stable immutable view of schema context associated with this Binding runtime context.
156 * @return stable view of schema context
158 public SchemaContext getSchemaContext() {
159 return this.schemaContext;
163 * Returns schema of augmentation
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
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.
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
181 * - ugmentation class
182 * @return Schema of augmentation or null if augmentaiton is not known in
184 * @throws IllegalArgumentException
185 * - if supplied class is not an augmentation
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));
193 * Returns defining {@link DataSchemaNode} for supplied class.
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.
200 * For getting augmentation schema from augmentation class use
201 * {@link #getAugmentationDefinition(Class)} instead.
204 * - class which represents list, container, choice or case.
205 * @return Schema node, from which class was generated.
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));
213 * Returns defining {@link AugmentationSchema} of target for supplied class.
216 * - {@link DataNodeContainer}
219 * @return entry of {@link AugmentationSchema} according to its identifier
220 * {@link AugmentationIdentifier}
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);
227 * FIXME: Validate augmentation schema lookup
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.
234 * If this augmentations have same definition, we emit same identifier
235 * with data and it is up to underlying user to validate data.
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());
251 realChilds.add(dataChildQNname);
252 childNames.add(child.getQName());
256 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
257 final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
258 return new SimpleEntry<>(identifier, proxy);
262 * Returns resolved case schema for supplied class
265 * - resolved parent choice schema
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
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);
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.
284 final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
285 (ChoiceCaseNode) origSchema);
289 private static Type referencedType(final Class<?> type) {
290 return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName(), true, null);
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);
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).
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.
310 public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
311 return getTypeWithSchema(referencedType(type));
314 public Entry<GeneratedType, Object> getTypeWithSchema(final String type) {
315 return getTypeWithSchema(referencedType(type));
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);
322 final Type definedType = this.typeToDefiningSchema.inverse().get(schema);
323 Preconditions.checkNotNull(definedType, "Failed to find defined type for %s schema %s", referencedType, schema);
325 if (definedType instanceof GeneratedTypeBuilder) {
326 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
328 Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType", referencedType);
329 return new SimpleEntry<>((GeneratedType) definedType,schema);
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);
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();
345 collectAllContainerTypes((GeneratedType) caze, caseChildren);
346 for (final Type caseChild : caseChildren) {
347 childToCase.put(caseChild, caseIdentifier);
351 return ImmutableMap.copyOf(childToCase);
355 * Map enum constants: yang - java
357 * @param enumClass enum generated class
358 * @return mapped enum constants from yang with their corresponding values in generated binding classes
360 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
361 final Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
362 return getEnumMapping(typeWithSchema);
366 * See {@link #getEnumMapping(Class)}}
368 public BiMap<String, String> getEnumMapping(final String enumClass) {
369 final Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
370 return getEnumMapping(typeWithSchema);
373 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, Object> typeWithSchema) {
374 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
376 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
377 final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
379 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
381 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
382 mappedEnums.put(enumPair.getName(),
383 JavaIdentifierNormalizer.normalizeSpecificIdentifier(enumPair.getName(), JavaIdentifier.CLASS));
386 // TODO cache these maps for future use
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) {
396 final Class<?> c = this.strategy.loadClass(caze);
398 } catch (final ClassNotFoundException e) {
399 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
405 public Class<?> getClassForSchema(final SchemaNode childSchema) {
406 final SchemaNode origSchema = getOriginalSchema(childSchema);
407 final Type clazzType = this.typeToDefiningSchema.inverse().get(origSchema);
409 return this.strategy.loadClass(clazzType);
410 } catch (final ClassNotFoundException e) {
411 throw new IllegalStateException(e);
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();
426 if (!augment.getChildNodes().isEmpty()) {
427 final Type augType = this.typeToDefiningSchema.inverse().get(augOrig);
428 if (augType != null) {
429 identifierToType.put(getAugmentationIdentifier(augment),augType);
435 return ImmutableMap.copyOf(identifierToType);
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());
443 return new AugmentationIdentifier(childNames);
446 private static Type referencedType(final Type type) {
447 if (type instanceof ReferencedTypeImpl) {
450 return new ReferencedTypeImpl(type.getPackageName(), type.getName(), true, null);
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];
459 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
460 collection.add(referencedType(childType));
463 for (final Type parent : type.getImplements()) {
464 if (parent instanceof GeneratedType) {
465 collectAllContainerTypes((GeneratedType) parent, collection);
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) {
480 public Class<?> getIdentityClass(final QName input) {
481 return this.identityClasses.getUnchecked(input);
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);
493 return key.getMethod(methodName);
496 @SuppressWarnings("rawtypes")
497 private static boolean isExplicitStatement(final ContainerSchemaNode node) {
498 return node instanceof EffectiveStatement
499 && ((EffectiveStatement) node).getDeclared().getStatementSource() == StatementSource.DECLARATION;