2 * Copyright (c) 2014 Cisco Systems, Inc. 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.yangtools.sal.binding.generator.util;
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;
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.yangtools.binding.generator.util.ReferencedTypeImpl;
31 import org.opendaylight.yangtools.concepts.Immutable;
32 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
33 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
34 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingSchemaContextUtils;
35 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
36 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
37 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature;
38 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
39 import org.opendaylight.yangtools.sal.binding.model.api.Type;
40 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
41 import org.opendaylight.yangtools.yang.binding.Augmentation;
42 import org.opendaylight.yangtools.yang.binding.BindingMapping;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
51 import org.opendaylight.yangtools.yang.model.api.Module;
52 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
53 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
55 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
56 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
57 import org.opendaylight.yangtools.yang.model.util.ExtendedType;
58 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
63 * Runtime Context for Java YANG Binding classes
66 * Runtime Context provides additional insight in Java YANG Binding,
67 * binding classes and underlying YANG schema, it contains
68 * runtime information, which could not be derived from generated
69 * classes alone using {@link org.opendaylight.yangtools.yang.binding.util.BindingReflections}.
71 * Some of this information are for example list of all available
72 * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
73 * choices are augmentable and new choices may be introduced by additional models.
75 * Same goes for all possible augmentations.
78 public class BindingRuntimeContext implements Immutable {
79 private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
80 private static final char DOT = '.';
81 private final ClassLoadingStrategy strategy;
82 private final SchemaContext schemaContext;
84 private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
85 private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
86 private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
87 private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
88 private final Map<QName, Type> identities = new HashMap<>();
90 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
91 new CacheLoader<QName, Class<?>>() {
93 public Class<?> load(final QName key) {
94 final Type identityType = identities.get(key);
95 Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
97 return strategy.loadClass(identityType);
98 } catch (final ClassNotFoundException e) {
99 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
104 private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
105 this.strategy = strategy;
106 this.schemaContext = schema;
108 final BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
109 generator.generateTypes(schema);
110 final Map<Module, ModuleContext> modules = generator.getModuleContexts();
112 for (final ModuleContext ctx : modules.values()) {
113 augmentationToSchema.putAll(ctx.getTypeToAugmentation());
114 typeToDefiningSchema.putAll(ctx.getTypeToSchema());
117 augmentableToAugmentations.putAll(ctx.getAugmentableToAugmentations());
118 choiceToCases.putAll(ctx.getChoiceToCases());
119 identities.putAll(ctx.getIdentities());
125 * Creates Binding Runtime Context from supplied class loading strategy and schema context.
127 * @param strategy Class loading strategy to retrieve generated Binding classes
128 * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
129 * @return Instance of BindingRuntimeContext for supplied schema context.
131 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
132 return new BindingRuntimeContext(strategy, ctx);
136 * Returns a class loading strategy associated with this binding runtime context
137 * which is used to load classes.
139 * @return Class loading strategy.
141 public ClassLoadingStrategy getStrategy() {
146 * Returns an stable immutable view of schema context associated with this Binding runtime context.
148 * @return stable view of schema context
150 public SchemaContext getSchemaContext() {
151 return schemaContext;
155 * Returns schema of augmentation
157 * Returned schema is schema definition from which augmentation class was generated.
158 * This schema is isolated from other augmentations. This means it contains
159 * augmentation definition as was present in original YANG module.
161 * Children of returned schema does not contain any additional augmentations,
162 * which may be present in runtime for them, thus returned schema is unsuitable
163 * for use for validation of data.
165 * For retrieving {@link AugmentationSchema}, which will contains
166 * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
167 * which will return augmentation schema derived from supplied augmentation target
170 * @param augClass Augmentation class
171 * @return Schema of augmentation or null if augmentaiton is not known in this context
172 * @throws IllegalArgumentException If supplied class is not an augmentation
174 public @Nullable AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
175 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
176 return augmentationToSchema.get(referencedType(augClass));
180 * Returns defining {@link DataSchemaNode} for supplied class.
183 * Returned schema is schema definition from which class was generated.
184 * This schema may be isolated from augmentations, if supplied class
185 * represent node, which was child of grouping or augmentation.
187 * For getting augmentation schema from augmentation class use
188 * {@link #getAugmentationDefinition(Class)} instead.
190 * @param cls Class which represents list, container, choice or case.
191 * @return Schema node, from which class was generated.
193 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
194 Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
195 return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
198 public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
199 final Class<? extends Augmentation<?>> aug) {
200 final AugmentationSchema origSchema = getAugmentationDefinition(aug);
201 Preconditions.checkArgument(origSchema != null, "Augmentation %s is not known in current schema context",aug);
203 * FIXME: Validate augmentation schema lookup
205 * Currently this algorithm, does not verify if instantiated child nodes
206 * are real one derived from augmentation schema. The problem with
207 * full validation is, if user used copy builders, he may use
208 * augmentation which was generated for different place.
210 * If this augmentations have same definition, we emit same identifier
211 * with data and it is up to underlying user to validate data.
214 final Set<QName> childNames = new HashSet<>();
215 final Set<DataSchemaNode> realChilds = new HashSet<>();
216 for (final DataSchemaNode child : origSchema.getChildNodes()) {
217 realChilds.add(target.getDataChildByName(child.getQName()));
218 childNames.add(child.getQName());
221 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
222 final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
223 return new AbstractMap.SimpleEntry<>(identifier, proxy);
228 * Returns resolved case schema for supplied class
230 * @param schema Resolved parent choice schema
231 * @param childClass Class representing case.
232 * @return Optionally a resolved case schema, absent if the choice is not legal in
234 * @throws IllegalArgumentException If supplied class does not represent case.
236 public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
237 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
238 Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
240 /* FIXME: Make sure that if there are multiple augmentations of same
241 * named case, with same structure we treat it as equals
242 * this is due property of Binding specification and copy builders
243 * that user may be unaware that he is using incorrect case
244 * which was generated for choice inside grouping.
246 final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
247 (ChoiceCaseNode) origSchema);
251 private static Type referencedType(final Class<?> type) {
252 return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
255 static Type referencedType(final String type) {
256 final int packageClassSeparator = type.lastIndexOf(DOT);
257 return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), type.substring(packageClassSeparator + 1));
261 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
262 * from which supplied class was generated. Returned schema may be augmented with
263 * additional information, which was not available at compile type
264 * (e.g. third party augmentations).
266 * @param type Binding Class for which schema should be retrieved.
267 * @return Instance of generated type (definition of Java API), along with
268 * {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
269 * which was used to generate supplied class.
271 public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
272 return getTypeWithSchema(referencedType(type));
275 public Entry<GeneratedType, Object> getTypeWithSchema(final String type) {
276 return getTypeWithSchema(referencedType(type));
279 private Entry<GeneratedType, Object> getTypeWithSchema(final Type referencedType) {
280 final Object schema = typeToDefiningSchema.get(referencedType);
281 final Type definedType = typeToDefiningSchema.inverse().get(schema);
282 Preconditions.checkNotNull(schema);
283 Preconditions.checkNotNull(definedType);
284 if(definedType instanceof GeneratedTypeBuilder) {
285 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
287 Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType", referencedType);
288 return new SimpleEntry<>((GeneratedType) definedType,schema);
291 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
292 final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();
293 for (final ChoiceSchemaNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
294 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
295 final Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
296 final Collection<Type> cases = choiceToCases.get(choiceType);
298 for (Type caze : cases) {
299 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
300 final HashSet<Type> caseChildren = new HashSet<>();
301 if (caze instanceof GeneratedTypeBuilder) {
302 caze = ((GeneratedTypeBuilder) caze).toInstance();
304 collectAllContainerTypes((GeneratedType) caze, caseChildren);
305 for (final Type caseChild : caseChildren) {
306 childToCase.put(caseChild, caseIdentifier);
310 return ImmutableMap.copyOf(childToCase);
314 * Map enum constants: yang - java
316 * @param enumClass enum generated class
317 * @return mapped enum constants from yang with their corresponding values in generated binding classes
319 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
320 final Map.Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
321 return getEnumMapping(typeWithSchema);
325 * See {@link #getEnumMapping(Class)}}
327 public BiMap<String, String> getEnumMapping(final String enumClass) {
328 final Map.Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
329 return getEnumMapping(typeWithSchema);
332 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, Object> typeWithSchema) {
333 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
335 final EnumTypeDefinition enumType;
336 if(typeDef instanceof ExtendedType) {
337 enumType = (EnumTypeDefinition) ((ExtendedType) typeDef).getBaseType();
339 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
340 enumType = (EnumTypeDefinition) typeDef;
343 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
345 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
346 mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
349 // TODO cache these maps for future use
353 public Set<Class<?>> getCases(final Class<?> choice) {
354 final Collection<Type> cazes = choiceToCases.get(referencedType(choice));
355 final Set<Class<?>> ret = new HashSet<>(cazes.size());
356 for(final Type caze : cazes) {
358 final Class<?> c = strategy.loadClass(caze);
360 } catch (final ClassNotFoundException e) {
361 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
367 public Class<?> getClassForSchema(final SchemaNode childSchema) {
368 final SchemaNode origSchema = getOriginalSchema(childSchema);
369 final Type clazzType = typeToDefiningSchema.inverse().get(origSchema);
371 return strategy.loadClass(clazzType);
372 } catch (final ClassNotFoundException e) {
373 throw new IllegalStateException(e);
377 public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
378 final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
379 if (container instanceof AugmentationTarget) {
380 final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
381 for (final AugmentationSchema augment : augments) {
382 // Augmentation must have child nodes if is to be used with Binding classes
383 AugmentationSchema augOrig = augment;
384 while (augOrig.getOriginalDefinition().isPresent()) {
385 augOrig = augOrig.getOriginalDefinition().get();
388 if (!augment.getChildNodes().isEmpty()) {
389 final Type augType = typeToDefiningSchema.inverse().get(augOrig);
390 if (augType != null) {
391 identifierToType.put(getAugmentationIdentifier(augment),augType);
397 return ImmutableMap.copyOf(identifierToType);
400 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
401 final Set<QName> childNames = new HashSet<>();
402 for (final DataSchemaNode child : augment.getChildNodes()) {
403 childNames.add(child.getQName());
405 return new AugmentationIdentifier(childNames);
408 private static Type referencedType(final Type type) {
409 if(type instanceof ReferencedTypeImpl) {
412 return new ReferencedTypeImpl(type.getPackageName(), type.getName());
415 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
416 for (final MethodSignature definition : type.getMethodDefinitions()) {
417 Type childType = definition.getReturnType();
418 if(childType instanceof ParameterizedType) {
419 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
421 if(childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
422 collection.add(referencedType(childType));
425 for (final Type parent : type.getImplements()) {
426 if (parent instanceof GeneratedType) {
427 collectAllContainerTypes((GeneratedType) parent, collection);
433 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
434 @SuppressWarnings("unchecked")
435 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
436 if (original != null) {
442 public Class<?> getIdentityClass(final QName input) {
443 return identityClasses.getUnchecked(input);