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.mdsal.binding.generator.util;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
13 import com.google.common.base.Optional;
14 import com.google.common.base.Preconditions;
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.BiMap;
19 import com.google.common.collect.HashBiMap;
20 import com.google.common.collect.ImmutableMap;
21 import com.google.common.collect.Iterables;
22 import java.util.AbstractMap.SimpleEntry;
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.HashMap;
26 import java.util.HashSet;
27 import java.util.Iterator;
28 import java.util.List;
30 import java.util.Map.Entry;
32 import javax.annotation.Nullable;
33 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeTypes;
34 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
35 import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
36 import org.opendaylight.mdsal.binding.generator.impl.BindingSchemaContextUtils;
37 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
38 import org.opendaylight.mdsal.binding.model.api.JavaTypeName;
39 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
40 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
41 import org.opendaylight.mdsal.binding.model.api.Type;
42 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
43 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
44 import org.opendaylight.yangtools.concepts.Immutable;
45 import org.opendaylight.yangtools.yang.binding.Augmentation;
46 import org.opendaylight.yangtools.yang.binding.BindingMapping;
47 import org.opendaylight.yangtools.yang.common.QName;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
49 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
51 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
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.DocumentedNode.WithStatus;
56 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
57 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
58 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
59 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
60 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
61 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
62 import org.slf4j.Logger;
63 import org.slf4j.LoggerFactory;
67 * Runtime Context for Java YANG Binding classes
70 * Runtime Context provides additional insight in Java YANG Binding,
71 * binding classes and underlying YANG schema, it contains
72 * runtime information, which could not be derived from generated
73 * classes alone using {@link org.opendaylight.yangtools.yang.binding.util.BindingReflections}.
75 * Some of this information are for example list of all available
76 * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
77 * choices are augmentable and new choices may be introduced by additional models.
79 * Same goes for all possible augmentations.
82 public class BindingRuntimeContext implements Immutable {
83 private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
84 private static final char DOT = '.';
86 private final BindingRuntimeTypes runtimeTypes;
87 private final ClassLoadingStrategy strategy;
88 private final SchemaContext schemaContext;
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 java.util.Optional<Type> identityType = runtimeTypes.findIdentity(key);
95 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
97 return strategy.loadClass(identityType.get());
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;
107 runtimeTypes = new BindingGeneratorImpl().generateTypeMapping(schema);
112 * Creates Binding Runtime Context from supplied class loading strategy and schema context.
114 * @param strategy Class loading strategy to retrieve generated Binding classes
115 * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
116 * @return Instance of BindingRuntimeContext for supplied schema context.
118 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
119 return new BindingRuntimeContext(strategy, ctx);
123 * Returns a class loading strategy associated with this binding runtime context
124 * which is used to load classes.
126 * @return Class loading strategy.
128 public ClassLoadingStrategy getStrategy() {
133 * Returns an stable immutable view of schema context associated with this Binding runtime context.
135 * @return stable view of schema context
137 public SchemaContext getSchemaContext() {
138 return schemaContext;
142 * Returns schema of augmentation
144 * Returned schema is schema definition from which augmentation class was generated.
145 * This schema is isolated from other augmentations. This means it contains
146 * augmentation definition as was present in original YANG module.
148 * Children of returned schema does not contain any additional augmentations,
149 * which may be present in runtime for them, thus returned schema is unsuitable
150 * for use for validation of data.
152 * For retrieving {@link AugmentationSchemaNode}, which will contains
153 * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
154 * which will return augmentation schema derived from supplied augmentation target
157 * @param augClass Augmentation class
158 * @return Schema of augmentation or null if augmentaiton is not known in this context
159 * @throws IllegalArgumentException If supplied class is not an augmentation
161 public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
162 checkArgument(Augmentation.class.isAssignableFrom(augClass),
163 "Class %s does not represent augmentation", augClass);
164 return runtimeTypes.findAugmentation(referencedType(augClass)).orElse(null);
168 * Returns defining {@link DataSchemaNode} for supplied class.
171 * Returned schema is schema definition from which class was generated.
172 * This schema may be isolated from augmentations, if supplied class
173 * represent node, which was child of grouping or augmentation.
175 * For getting augmentation schema from augmentation class use
176 * {@link #getAugmentationDefinition(Class)} instead.
178 * @param cls Class which represents list, container, choice or case.
179 * @return Schema node, from which class was generated.
181 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
182 checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be augmentation (%s is)",
184 return (DataSchemaNode) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
187 public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
188 final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
189 final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
190 checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
192 * FIXME: Validate augmentation schema lookup
194 * Currently this algorithm, does not verify if instantiated child nodes
195 * are real one derived from augmentation schema. The problem with
196 * full validation is, if user used copy builders, he may use
197 * augmentation which was generated for different place.
199 * If this augmentations have same definition, we emit same identifier
200 * with data and it is up to underlying user to validate data.
203 final Set<QName> childNames = new HashSet<>();
204 final Set<DataSchemaNode> realChilds = new HashSet<>();
205 for (final DataSchemaNode child : origSchema.getChildNodes()) {
206 final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
207 final String childLocalName = child.getQName().getLocalName();
208 if (dataChildQNname == null) {
209 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
210 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
211 realChilds.add(dataSchemaNode);
212 childNames.add(dataSchemaNode.getQName());
216 realChilds.add(dataChildQNname);
217 childNames.add(child.getQName());
221 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
222 final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
223 return new 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<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
237 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
238 checkArgument(origSchema instanceof CaseSchemaNode, "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<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
247 (CaseSchemaNode) origSchema);
251 private static Type referencedType(final Class<?> type) {
252 return new ReferencedTypeImpl(JavaTypeName.create(type));
256 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
257 * from which supplied class was generated. Returned schema may be augmented with
258 * additional information, which was not available at compile type
259 * (e.g. third party augmentations).
261 * @param type Binding Class for which schema should be retrieved.
262 * @return Instance of generated type (definition of Java API), along with
263 * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
264 * which was used to generate supplied class.
266 public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
267 return getTypeWithSchema(referencedType(type));
270 private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
271 final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
272 () -> new NullPointerException("Failed to find schema for type " + referencedType));
273 final Type definedType = runtimeTypes.findType(schema).orElseThrow(
274 () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
276 if (definedType instanceof GeneratedTypeBuilder) {
277 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
279 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
280 return new SimpleEntry<>((GeneratedType) definedType, schema);
283 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
284 final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
286 for (final ChoiceSchemaNode choice : Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
287 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
288 final java.util.Optional<Type> optType = runtimeTypes.findType(originalChoice);
289 checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
290 final Type choiceType = optType.get();
292 for (Type caze : runtimeTypes.findCases(referencedType(choiceType))) {
293 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
294 final HashSet<Type> caseChildren = new HashSet<>();
295 if (caze instanceof GeneratedTypeBuilder) {
296 caze = ((GeneratedTypeBuilder) caze).build();
298 collectAllContainerTypes((GeneratedType) caze, caseChildren);
299 for (final Type caseChild : caseChildren) {
300 childToCase.put(caseChild, caseIdentifier);
304 return ImmutableMap.copyOf(childToCase);
308 * Map enum constants: yang - java
310 * @param enumClass enum generated class
311 * @return mapped enum constants from yang with their corresponding values in generated binding classes
313 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
314 final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
315 return getEnumMapping(typeWithSchema);
319 * Map enum constants: yang - java
321 * @param enumClassName enum generated class name
322 * @return mapped enum constants from yang with their corresponding values in generated binding classes
324 public BiMap<String, String> getEnumMapping(final String enumClassName) {
325 return getEnumMapping(findTypeWithSchema(enumClassName));
328 private Entry<GeneratedType, WithStatus> findTypeWithSchema(final String className) {
329 // All we have is a straight FQCN, which we need to split into a hierarchical JavaTypeName. This involves
330 // some amount of guesswork -- we do that by peeling components at the dot and trying out, e.g. given
331 // "foo.bar.baz.Foo.Bar.Baz" we end up trying:
332 // "foo.bar.baz.Foo.Bar" + "Baz"
333 // "foo.bar.baz.Foo" + Bar" + "Baz"
334 // "foo.bar.baz" + Foo" + Bar" + "Baz"
336 // And see which one sticks. We cannot rely on capital letters, as they can be used in package names, too.
337 // Nested classes are not common, so we should be arriving at the result pretty quickly.
338 final List<String> components = new ArrayList<>();
339 String packageName = className;
341 for (int lastDot = packageName.lastIndexOf(DOT); lastDot != -1; lastDot = packageName.lastIndexOf(DOT)) {
342 components.add(packageName.substring(lastDot + 1));
343 packageName = packageName.substring(0, lastDot);
345 final Iterator<String> it = components.iterator();
346 JavaTypeName name = JavaTypeName.create(packageName, it.next());
347 while (it.hasNext()) {
348 name = name.createEnclosed(it.next());
351 final Type type = new ReferencedTypeImpl(name);
352 final java.util.Optional<WithStatus> optSchema = runtimeTypes.findSchema(type);
353 if (!optSchema.isPresent()) {
357 final WithStatus schema = optSchema.get();
358 final java.util.Optional<Type> optDefinedType = runtimeTypes.findType(schema);
359 if (!optDefinedType.isPresent()) {
363 final Type definedType = optDefinedType.get();
364 if (definedType instanceof GeneratedTypeBuilder) {
365 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
367 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", className);
368 return new SimpleEntry<>((GeneratedType) definedType, schema);
371 throw new IllegalArgumentException("Failed to find type for " + className);
374 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
375 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
377 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
378 final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
380 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
382 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
383 mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
386 // TODO cache these maps for future use
390 public Set<Class<?>> getCases(final Class<?> choice) {
391 final Collection<Type> cazes = runtimeTypes.findCases(referencedType(choice));
392 final Set<Class<?>> ret = new HashSet<>(cazes.size());
393 for(final Type caze : cazes) {
395 final Class<?> c = strategy.loadClass(caze);
397 } catch (final ClassNotFoundException e) {
398 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
404 public Class<?> getClassForSchema(final SchemaNode childSchema) {
405 final SchemaNode origSchema = getOriginalSchema(childSchema);
406 final java.util.Optional<Type> clazzType = runtimeTypes.findType(origSchema);
407 checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
408 childSchema, origSchema);
411 return strategy.loadClass(clazzType.get());
412 } catch (final ClassNotFoundException e) {
413 throw new IllegalStateException(e);
417 public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
418 final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
419 if (container instanceof AugmentationTarget) {
420 final Set<AugmentationSchemaNode> augments = ((AugmentationTarget) container).getAvailableAugmentations();
421 for (final AugmentationSchemaNode augment : augments) {
422 // Augmentation must have child nodes if is to be used with Binding classes
423 AugmentationSchemaNode augOrig = augment;
424 while (augOrig.getOriginalDefinition().isPresent()) {
425 augOrig = augOrig.getOriginalDefinition().get();
428 if (!augment.getChildNodes().isEmpty()) {
429 final java.util.Optional<Type> augType = runtimeTypes.findType(augOrig);
430 if (augType.isPresent()) {
431 identifierToType.put(getAugmentationIdentifier(augment), augType.get());
437 return ImmutableMap.copyOf(identifierToType);
440 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
441 final Set<QName> childNames = new HashSet<>();
442 for (final DataSchemaNode child : augment.getChildNodes()) {
443 childNames.add(child.getQName());
445 return new AugmentationIdentifier(childNames);
448 private static Type referencedType(final Type type) {
449 if (type instanceof ReferencedTypeImpl) {
452 return new ReferencedTypeImpl(type.getIdentifier());
455 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
456 for (final MethodSignature definition : type.getMethodDefinitions()) {
457 Type childType = definition.getReturnType();
458 if (childType instanceof ParameterizedType) {
459 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
461 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
462 collection.add(referencedType(childType));
465 for (final Type parent : type.getImplements()) {
466 if (parent instanceof GeneratedType) {
467 collectAllContainerTypes((GeneratedType) parent, collection);
473 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
474 @SuppressWarnings("unchecked")
475 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
476 if (original != null) {
482 public Class<?> getIdentityClass(final QName input) {
483 return identityClasses.getUnchecked(input);