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.mdsal.binding.spec.naming.BindingMapping;
45 import org.opendaylight.yangtools.concepts.Immutable;
46 import org.opendaylight.yangtools.yang.binding.Action;
47 import org.opendaylight.yangtools.yang.binding.Augmentation;
48 import org.opendaylight.yangtools.yang.common.QName;
49 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
50 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
51 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
53 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
54 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
56 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
57 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
58 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
59 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
60 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
61 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
62 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
63 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
64 import org.slf4j.Logger;
65 import org.slf4j.LoggerFactory;
68 * Runtime Context for Java YANG Binding classes
70 * <p>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.mdsal.binding.spec.reflect.BindingReflections}.
75 * <p>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 * <p>Same goes for all possible augmentations.
81 public final 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);
111 * Creates Binding Runtime Context from supplied class loading strategy and schema context.
113 * @param strategy Class loading strategy to retrieve generated Binding classes
114 * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
115 * @return Instance of BindingRuntimeContext for supplied schema context.
117 public static BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
118 return new BindingRuntimeContext(strategy, ctx);
122 * Returns a class loading strategy associated with this binding runtime context
123 * which is used to load classes.
125 * @return Class loading strategy.
127 public ClassLoadingStrategy getStrategy() {
132 * Returns an stable immutable view of schema context associated with this Binding runtime context.
134 * @return stable view of schema context
136 public SchemaContext getSchemaContext() {
137 return schemaContext;
141 * Returns schema of augmentation.
143 * <p>Returned schema is schema definition from which augmentation class was generated.
144 * This schema is isolated from other augmentations. This means it contains
145 * augmentation definition as was present in original YANG module.
147 * <p>Children of returned schema does not contain any additional augmentations,
148 * which may be present in runtime for them, thus returned schema is unsuitable
149 * for use for validation of data.
151 * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
152 * full model for child nodes, you should use method
153 * {@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.
170 * <p>Returned schema is schema definition from which class was generated.
171 * This schema may be isolated from augmentations, if supplied class
172 * represent node, which was child of grouping or augmentation.
174 * <p>For getting augmentation schema from augmentation class use
175 * {@link #getAugmentationDefinition(Class)} instead.
177 * @param cls Class which represents list, container, choice or case.
178 * @return Schema node, from which class was generated.
180 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
181 checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
183 checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
184 return (DataSchemaNode) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
187 public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
188 return (ActionDefinition) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
191 public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
192 final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
193 final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
194 checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
196 * FIXME: Validate augmentation schema lookup
198 * Currently this algorithm, does not verify if instantiated child nodes
199 * are real one derived from augmentation schema. The problem with
200 * full validation is, if user used copy builders, he may use
201 * augmentation which was generated for different place.
203 * If this augmentations have same definition, we emit same identifier
204 * with data and it is up to underlying user to validate data.
207 final Set<QName> childNames = new HashSet<>();
208 final Set<DataSchemaNode> realChilds = new HashSet<>();
209 for (final DataSchemaNode child : origSchema.getChildNodes()) {
210 final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
211 final String childLocalName = child.getQName().getLocalName();
212 if (dataChildQNname == null) {
213 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
214 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
215 realChilds.add(dataSchemaNode);
216 childNames.add(dataSchemaNode.getQName());
220 realChilds.add(dataChildQNname);
221 childNames.add(child.getQName());
225 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
226 final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
227 return new SimpleEntry<>(identifier, proxy);
231 * Returns resolved case schema for supplied class.
233 * @param schema Resolved parent choice schema
234 * @param childClass Class representing case.
235 * @return Optionally a resolved case schema, absent if the choice is not legal in
237 * @throws IllegalArgumentException If supplied class does not represent case.
239 public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
240 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
241 checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
243 /* FIXME: Make sure that if there are multiple augmentations of same
244 * named case, with same structure we treat it as equals
245 * this is due property of Binding specification and copy builders
246 * that user may be unaware that he is using incorrect case
247 * which was generated for choice inside grouping.
249 final Optional<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
250 (CaseSchemaNode) origSchema);
254 private static Type referencedType(final Class<?> type) {
255 return new ReferencedTypeImpl(JavaTypeName.create(type));
259 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
260 * from which supplied class was generated. Returned schema may be augmented with
261 * additional information, which was not available at compile type
262 * (e.g. third party augmentations).
264 * @param type Binding Class for which schema should be retrieved.
265 * @return Instance of generated type (definition of Java API), along with
266 * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
267 * which was used to generate supplied class.
269 public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
270 return getTypeWithSchema(referencedType(type));
273 private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
274 final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
275 () -> new NullPointerException("Failed to find schema for type " + referencedType));
276 final Type definedType = runtimeTypes.findType(schema).orElseThrow(
277 () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
279 if (definedType instanceof GeneratedTypeBuilder) {
280 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
282 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
283 return new SimpleEntry<>((GeneratedType) definedType, schema);
286 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
287 final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
289 for (final ChoiceSchemaNode choice : Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
290 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
291 final java.util.Optional<Type> optType = runtimeTypes.findType(originalChoice);
292 checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
293 final Type choiceType = optType.get();
295 for (Type caze : runtimeTypes.findCases(referencedType(choiceType))) {
296 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
297 final HashSet<Type> caseChildren = new HashSet<>();
298 if (caze instanceof GeneratedTypeBuilder) {
299 caze = ((GeneratedTypeBuilder) caze).build();
301 collectAllContainerTypes((GeneratedType) caze, caseChildren);
302 for (final Type caseChild : caseChildren) {
303 childToCase.put(caseChild, caseIdentifier);
307 return ImmutableMap.copyOf(childToCase);
311 * Map enum constants: yang - java.
313 * @param enumClass enum generated class
314 * @return mapped enum constants from yang with their corresponding values in generated binding classes
316 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
317 final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
318 return getEnumMapping(typeWithSchema);
322 * Map enum constants: yang - java.
324 * @param enumClassName enum generated class name
325 * @return mapped enum constants from yang with their corresponding values in generated binding classes
327 public BiMap<String, String> getEnumMapping(final String enumClassName) {
328 return getEnumMapping(findTypeWithSchema(enumClassName));
331 private Entry<GeneratedType, WithStatus> findTypeWithSchema(final String className) {
332 // All we have is a straight FQCN, which we need to split into a hierarchical JavaTypeName. This involves
333 // some amount of guesswork -- we do that by peeling components at the dot and trying out, e.g. given
334 // "foo.bar.baz.Foo.Bar.Baz" we end up trying:
335 // "foo.bar.baz.Foo.Bar" + "Baz"
336 // "foo.bar.baz.Foo" + Bar" + "Baz"
337 // "foo.bar.baz" + Foo" + Bar" + "Baz"
339 // And see which one sticks. We cannot rely on capital letters, as they can be used in package names, too.
340 // Nested classes are not common, so we should be arriving at the result pretty quickly.
341 final List<String> components = new ArrayList<>();
342 String packageName = className;
344 for (int lastDot = packageName.lastIndexOf(DOT); lastDot != -1; lastDot = packageName.lastIndexOf(DOT)) {
345 components.add(packageName.substring(lastDot + 1));
346 packageName = packageName.substring(0, lastDot);
348 final Iterator<String> it = components.iterator();
349 JavaTypeName name = JavaTypeName.create(packageName, it.next());
350 while (it.hasNext()) {
351 name = name.createEnclosed(it.next());
354 final Type type = new ReferencedTypeImpl(name);
355 final java.util.Optional<WithStatus> optSchema = runtimeTypes.findSchema(type);
356 if (!optSchema.isPresent()) {
360 final WithStatus schema = optSchema.get();
361 final java.util.Optional<Type> optDefinedType = runtimeTypes.findType(schema);
362 if (!optDefinedType.isPresent()) {
366 final Type definedType = optDefinedType.get();
367 if (definedType instanceof GeneratedTypeBuilder) {
368 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
370 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", className);
371 return new SimpleEntry<>((GeneratedType) definedType, schema);
374 throw new IllegalArgumentException("Failed to find type for " + className);
377 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
378 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
380 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
381 final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
383 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
385 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
386 mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
389 // TODO cache these maps for future use
393 public Set<Class<?>> getCases(final Class<?> choice) {
394 final Collection<Type> cazes = runtimeTypes.findCases(referencedType(choice));
395 final Set<Class<?>> ret = new HashSet<>(cazes.size());
396 for (final Type caze : cazes) {
398 final Class<?> c = strategy.loadClass(caze);
400 } catch (final ClassNotFoundException e) {
401 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
407 public Class<?> getClassForSchema(final SchemaNode childSchema) {
408 final SchemaNode origSchema = getOriginalSchema(childSchema);
409 final java.util.Optional<Type> clazzType = runtimeTypes.findType(origSchema);
410 checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
411 childSchema, origSchema);
414 return strategy.loadClass(clazzType.get());
415 } catch (final ClassNotFoundException e) {
416 throw new IllegalStateException(e);
420 public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
421 final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
422 if (container instanceof AugmentationTarget) {
423 final Set<AugmentationSchemaNode> augments = ((AugmentationTarget) container).getAvailableAugmentations();
424 for (final AugmentationSchemaNode augment : augments) {
425 // Augmentation must have child nodes if is to be used with Binding classes
426 AugmentationSchemaNode augOrig = augment;
427 while (augOrig.getOriginalDefinition().isPresent()) {
428 augOrig = augOrig.getOriginalDefinition().get();
431 if (!augment.getChildNodes().isEmpty()) {
432 final java.util.Optional<Type> augType = runtimeTypes.findType(augOrig);
433 if (augType.isPresent()) {
434 identifierToType.put(getAugmentationIdentifier(augment), augType.get());
440 return ImmutableMap.copyOf(identifierToType);
443 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
444 final Set<QName> childNames = new HashSet<>();
445 for (final DataSchemaNode child : augment.getChildNodes()) {
446 childNames.add(child.getQName());
448 return new AugmentationIdentifier(childNames);
451 private static Type referencedType(final Type type) {
452 if (type instanceof ReferencedTypeImpl) {
455 return new ReferencedTypeImpl(type.getIdentifier());
458 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
459 for (final MethodSignature definition : type.getMethodDefinitions()) {
460 Type childType = definition.getReturnType();
461 if (childType instanceof ParameterizedType) {
462 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
464 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
465 collection.add(referencedType(childType));
468 for (final Type parent : type.getImplements()) {
469 if (parent instanceof GeneratedType) {
470 collectAllContainerTypes((GeneratedType) parent, collection);
476 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
477 @SuppressWarnings("unchecked")
478 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
479 if (original != null) {
485 public Class<?> getIdentityClass(final QName input) {
486 return identityClasses.getUnchecked(input);