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.util.AbstractMap.SimpleEntry;
23 import java.util.Collection;
24 import java.util.HashMap;
25 import java.util.HashSet;
27 import java.util.Map.Entry;
29 import javax.annotation.Nullable;
30 import org.opendaylight.mdsal.binding.javav2.generator.api.ClassLoadingStrategy;
31 import org.opendaylight.mdsal.binding.javav2.generator.impl.BindingGeneratorImpl;
32 import org.opendaylight.mdsal.binding.javav2.generator.impl.ModuleContext;
33 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifier;
34 import org.opendaylight.mdsal.binding.javav2.generator.util.JavaIdentifierNormalizer;
35 import org.opendaylight.mdsal.binding.javav2.generator.util.ReferencedTypeImpl;
36 import org.opendaylight.mdsal.binding.javav2.model.api.GeneratedType;
37 import org.opendaylight.mdsal.binding.javav2.model.api.MethodSignature;
38 import org.opendaylight.mdsal.binding.javav2.model.api.ParameterizedType;
39 import org.opendaylight.mdsal.binding.javav2.model.api.Type;
40 import org.opendaylight.mdsal.binding.javav2.model.api.type.builder.GeneratedTypeBuilder;
41 import org.opendaylight.mdsal.binding.javav2.runtime.context.util.BindingSchemaContextUtils;
42 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
43 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
44 import org.opendaylight.yangtools.concepts.Immutable;
45 import org.opendaylight.yangtools.yang.common.QName;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
48 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
49 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
50 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.Module;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
57 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
58 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
59 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
64 * Runtime Context for Java YANG Binding classes
67 * Runtime Context provides additional insight in Java YANG Binding, binding
68 * classes and underlying YANG schema, it contains runtime information, which
69 * could not be derived from generated classes alone using
70 * {@link BindingReflections}.
72 * Some of this information are for example list of all available children for
73 * cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are
74 * augmentable and new choices may be introduced by additional models.
76 * Same goes for all possible augmentations.
80 public class BindingRuntimeContext implements Immutable {
82 private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
83 private static final char DOT = '.';
84 private final ClassLoadingStrategy strategy;
85 private final SchemaContext schemaContext;
87 private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
88 private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
89 private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
90 private final Map<QName, Type> identities = new HashMap<>();
92 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
93 new CacheLoader<QName, Class<?>>() {
95 public Class<?> load(final QName key) {
96 final Type identityType = BindingRuntimeContext.this.identities.get(key);
97 Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
99 return BindingRuntimeContext.this.strategy.loadClass(identityType);
100 } catch (final ClassNotFoundException e) {
101 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
106 private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
107 this.strategy = strategy;
108 this.schemaContext = schema;
110 final BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
111 final Map<Module, ModuleContext> modules = generator.getModuleContexts(this.schemaContext);
113 for (final ModuleContext ctx : modules.values()) {
114 this.augmentationToSchema.putAll(ctx.getTypeToAugmentation());
115 this.typeToDefiningSchema.putAll(ctx.getTypeToSchema());
118 this.choiceToCases.putAll(ctx.getChoiceToCases());
119 this.identities.putAll(ctx.getIdentities());
124 * Creates Binding Runtime Context from supplied class loading strategy and
128 * - class loading strategy to retrieve generated Binding classes
130 * - schema context which describes YANG model and to which
131 * Binding classes should be mapped
132 * @return Instance of BindingRuntimeContext for supplied schema context.
134 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
135 return new BindingRuntimeContext(strategy, ctx);
139 * Returns a class loading strategy associated with this binding runtime context
140 * which is used to load classes.
142 * @return Class loading strategy.
144 public ClassLoadingStrategy getStrategy() {
145 return this.strategy;
149 * Returns an stable immutable view of schema context associated with this Binding runtime context.
151 * @return stable view of schema context
153 public SchemaContext getSchemaContext() {
154 return this.schemaContext;
158 * Returns schema of augmentation
160 * Returned schema is schema definition from which augmentation class was
161 * generated. This schema is isolated from other augmentations. This means
162 * it contains augmentation definition as was present in original YANG
165 * Children of returned schema does not contain any additional
166 * augmentations, which may be present in runtime for them, thus returned
167 * schema is unsuitable for use for validation of data.
169 * For retrieving {@link AugmentationSchema}, which will contains full model
170 * for child nodes, you should use method
171 * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)} which
172 * will return augmentation schema derived from supplied augmentation target
176 * - ugmentation class
177 * @return Schema of augmentation or null if augmentaiton is not known in
179 * @throws IllegalArgumentException
180 * - if supplied class is not an augmentation
182 public @Nullable AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
183 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
184 return this.augmentationToSchema.get(referencedType(augClass));
188 * Returns defining {@link DataSchemaNode} for supplied class.
191 * Returned schema is schema definition from which class was generated. This
192 * schema may be isolated from augmentations, if supplied class represent
193 * node, which was child of grouping or augmentation.
195 * For getting augmentation schema from augmentation class use
196 * {@link #getAugmentationDefinition(Class)} instead.
199 * - class which represents list, container, choice or case.
200 * @return Schema node, from which class was generated.
202 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
203 Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
204 return (DataSchemaNode) this.typeToDefiningSchema.get(referencedType(cls));
208 * Returns defining {@link AugmentationSchema} of target for supplied class.
211 * - {@link DataNodeContainer}
214 * @return entry of {@link AugmentationSchema} according to its identifier
215 * {@link AugmentationIdentifier}
217 public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
218 final Class<? extends Augmentation<?>> aug) {
219 final AugmentationSchema origSchema = getAugmentationDefinition(aug);
220 Preconditions.checkArgument(origSchema != null, "Augmentation %s is not known in current schema context",aug);
222 * FIXME: Validate augmentation schema lookup
224 * Currently this algorithm, does not verify if instantiated child nodes
225 * are real one derived from augmentation schema. The problem with full
226 * validation is, if user used copy builders, he may use augmentation
227 * which was generated for different place.
229 * If this augmentations have same definition, we emit same identifier
230 * with data and it is up to underlying user to validate data.
233 final Set<QName> childNames = new HashSet<>();
234 final Set<DataSchemaNode> realChilds = new HashSet<>();
235 for (final DataSchemaNode child : origSchema.getChildNodes()) {
236 final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
237 final String childLocalName = child.getQName().getLocalName();
238 if (dataChildQNname == null) {
239 for (final DataSchemaNode dataSchemaNode : target.getChildNodes()) {
240 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
241 realChilds.add(dataSchemaNode);
242 childNames.add(dataSchemaNode.getQName());
246 realChilds.add(dataChildQNname);
247 childNames.add(child.getQName());
251 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
252 final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
253 return new SimpleEntry<>(identifier, proxy);
257 * Returns resolved case schema for supplied class
260 * - resolved parent choice schema
262 * - class representing case.
263 * @return Optionally a resolved case schema, absent if the choice is not
264 * legal in the given context.
265 * @throws IllegalArgumentException
266 * - if supplied class does not represent case
268 public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
269 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
270 Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
273 * FIXME: Make sure that if there are multiple augmentations of same
274 * named case, with same structure we treat it as equals this is due
275 * property of Binding specification and copy builders that user may be
276 * unaware that he is using incorrect case which was generated for
277 * choice inside grouping.
279 final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
280 (ChoiceCaseNode) origSchema);
284 private static Type referencedType(final Class<?> type) {
285 return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
288 static Type referencedType(final String type) {
289 final int packageClassSeparator = type.lastIndexOf(DOT);
290 return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), type.substring(packageClassSeparator + 1));
294 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
295 * from which supplied class was generated. Returned schema may be augmented with
296 * additional information, which was not available at compile type
297 * (e.g. third party augmentations).
299 * @param type Binding Class for which schema should be retrieved.
300 * @return Instance of generated type (definition of Java API), along with
301 * {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
302 * which was used to generate supplied class.
304 public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
305 return getTypeWithSchema(referencedType(type));
308 public Entry<GeneratedType, Object> getTypeWithSchema(final String type) {
309 return getTypeWithSchema(referencedType(type));
312 private Entry<GeneratedType, Object> getTypeWithSchema(final Type referencedType) {
313 final Object schema = this.typeToDefiningSchema.get(referencedType);
314 Preconditions.checkNotNull(schema, "Failed to find schema for type %s", referencedType);
316 final Type definedType = this.typeToDefiningSchema.inverse().get(schema);
317 Preconditions.checkNotNull(definedType, "Failed to find defined type for %s schema %s", referencedType, schema);
319 if (definedType instanceof GeneratedTypeBuilder) {
320 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
322 Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType", referencedType);
323 return new SimpleEntry<>((GeneratedType) definedType,schema);
326 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
327 final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();
328 for (final ChoiceSchemaNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
329 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
330 final Type choiceType = referencedType(this.typeToDefiningSchema.inverse().get(originalChoice));
331 final Collection<Type> cases = this.choiceToCases.get(choiceType);
333 for (Type caze : cases) {
334 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
335 final HashSet<Type> caseChildren = new HashSet<>();
336 if (caze instanceof GeneratedTypeBuilder) {
337 caze = ((GeneratedTypeBuilder) caze).toInstance();
339 collectAllContainerTypes((GeneratedType) caze, caseChildren);
340 for (final Type caseChild : caseChildren) {
341 childToCase.put(caseChild, caseIdentifier);
345 return ImmutableMap.copyOf(childToCase);
349 * Map enum constants: yang - java
351 * @param enumClass enum generated class
352 * @return mapped enum constants from yang with their corresponding values in generated binding classes
354 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
355 final Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
356 return getEnumMapping(typeWithSchema);
360 * See {@link #getEnumMapping(Class)}}
362 public BiMap<String, String> getEnumMapping(final String enumClass) {
363 final Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
364 return getEnumMapping(typeWithSchema);
367 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, Object> typeWithSchema) {
368 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
370 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
371 final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
373 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
375 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
376 mappedEnums.put(enumPair.getName(),
377 JavaIdentifierNormalizer.normalizeSpecificIdentifier(enumPair.getName(), JavaIdentifier.CLASS));
380 // TODO cache these maps for future use
385 public Set<Class<?>> getCases(final Class<?> choice) {
386 final Collection<Type> cazes = this.choiceToCases.get(referencedType(choice));
387 final Set<Class<?>> ret = new HashSet<>(cazes.size());
388 for(final Type caze : cazes) {
390 final Class<?> c = this.strategy.loadClass(caze);
392 } catch (final ClassNotFoundException e) {
393 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
399 public Class<?> getClassForSchema(final SchemaNode childSchema) {
400 final SchemaNode origSchema = getOriginalSchema(childSchema);
401 final Type clazzType = this.typeToDefiningSchema.inverse().get(origSchema);
403 return this.strategy.loadClass(clazzType);
404 } catch (final ClassNotFoundException e) {
405 throw new IllegalStateException(e);
409 public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
410 final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
411 if (container instanceof AugmentationTarget) {
412 final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
413 for (final AugmentationSchema augment : augments) {
414 // Augmentation must have child nodes if is to be used with Binding classes
415 AugmentationSchema augOrig = augment;
416 while (augOrig.getOriginalDefinition().isPresent()) {
417 augOrig = augOrig.getOriginalDefinition().get();
420 if (!augment.getChildNodes().isEmpty()) {
421 final Type augType = this.typeToDefiningSchema.inverse().get(augOrig);
422 if (augType != null) {
423 identifierToType.put(getAugmentationIdentifier(augment),augType);
429 return ImmutableMap.copyOf(identifierToType);
432 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
433 final Set<QName> childNames = new HashSet<>();
434 for (final DataSchemaNode child : augment.getChildNodes()) {
435 childNames.add(child.getQName());
437 return new AugmentationIdentifier(childNames);
440 private static Type referencedType(final Type type) {
441 if (type instanceof ReferencedTypeImpl) {
444 return new ReferencedTypeImpl(type.getPackageName(), type.getName());
447 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
448 for (final MethodSignature definition : type.getMethodDefinitions()) {
449 Type childType = definition.getReturnType();
450 if (childType instanceof ParameterizedType) {
451 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
453 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
454 collection.add(referencedType(childType));
457 for (final Type parent : type.getImplements()) {
458 if (parent instanceof GeneratedType) {
459 collectAllContainerTypes((GeneratedType) parent, collection);
465 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
466 @SuppressWarnings("unchecked")
467 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
468 if (original != null) {
474 public Class<?> getIdentityClass(final QName input) {
475 return this.identityClasses.getUnchecked(input);