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.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.generator.api.BindingRuntimeTypes;
31 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
32 import org.opendaylight.mdsal.binding.generator.impl.BindingGeneratorImpl;
33 import org.opendaylight.mdsal.binding.generator.impl.BindingSchemaContextUtils;
34 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
35 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
36 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
37 import org.opendaylight.mdsal.binding.model.api.Type;
38 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
39 import org.opendaylight.mdsal.binding.model.util.ReferencedTypeImpl;
40 import org.opendaylight.yangtools.concepts.Immutable;
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.AugmentationSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
47 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
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.DocumentedNode.WithStatus;
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.SchemaNodeUtils;
58 import org.slf4j.Logger;
59 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 = '.';
82 private final BindingRuntimeTypes runtimeTypes;
83 private final ClassLoadingStrategy strategy;
84 private final SchemaContext schemaContext;
86 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
87 new CacheLoader<QName, Class<?>>() {
89 public Class<?> load(final QName key) {
90 final java.util.Optional<Type> identityType = runtimeTypes.findIdentity(key);
91 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
93 return strategy.loadClass(identityType.get());
94 } catch (final ClassNotFoundException e) {
95 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
100 private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
101 this.strategy = strategy;
102 this.schemaContext = schema;
103 runtimeTypes = new BindingGeneratorImpl().generateTypeMapping(schema);
108 * Creates Binding Runtime Context from supplied class loading strategy and schema context.
110 * @param strategy Class loading strategy to retrieve generated Binding classes
111 * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
112 * @return Instance of BindingRuntimeContext for supplied schema context.
114 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
115 return new BindingRuntimeContext(strategy, ctx);
119 * Returns a class loading strategy associated with this binding runtime context
120 * which is used to load classes.
122 * @return Class loading strategy.
124 public ClassLoadingStrategy getStrategy() {
129 * Returns an stable immutable view of schema context associated with this Binding runtime context.
131 * @return stable view of schema context
133 public SchemaContext getSchemaContext() {
134 return schemaContext;
138 * Returns schema of augmentation
140 * Returned schema is schema definition from which augmentation class was generated.
141 * This schema is isolated from other augmentations. This means it contains
142 * augmentation definition as was present in original YANG module.
144 * Children of returned schema does not contain any additional augmentations,
145 * which may be present in runtime for them, thus returned schema is unsuitable
146 * for use for validation of data.
148 * For retrieving {@link AugmentationSchemaNode}, which will contains
149 * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
150 * which will return augmentation schema derived from supplied augmentation target
153 * @param augClass Augmentation class
154 * @return Schema of augmentation or null if augmentaiton is not known in this context
155 * @throws IllegalArgumentException If supplied class is not an augmentation
157 public @Nullable AugmentationSchemaNode getAugmentationDefinition(final Class<?> augClass) {
158 checkArgument(Augmentation.class.isAssignableFrom(augClass),
159 "Class %s does not represent augmentation", augClass);
160 return runtimeTypes.findAugmentation(referencedType(augClass)).orElse(null);
164 * Returns defining {@link DataSchemaNode} for supplied class.
167 * Returned schema is schema definition from which class was generated.
168 * This schema may be isolated from augmentations, if supplied class
169 * represent node, which was child of grouping or augmentation.
171 * For getting augmentation schema from augmentation class use
172 * {@link #getAugmentationDefinition(Class)} instead.
174 * @param cls Class which represents list, container, choice or case.
175 * @return Schema node, from which class was generated.
177 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
178 checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be augmentation (%s is)",
180 return (DataSchemaNode) runtimeTypes.findSchema(referencedType(cls)).orElse(null);
183 public Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
184 final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
185 final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
186 checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
188 * FIXME: Validate augmentation schema lookup
190 * Currently this algorithm, does not verify if instantiated child nodes
191 * are real one derived from augmentation schema. The problem with
192 * full validation is, if user used copy builders, he may use
193 * augmentation which was generated for different place.
195 * If this augmentations have same definition, we emit same identifier
196 * with data and it is up to underlying user to validate data.
199 final Set<QName> childNames = new HashSet<>();
200 final Set<DataSchemaNode> realChilds = new HashSet<>();
201 for (final DataSchemaNode child : origSchema.getChildNodes()) {
202 final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
203 final String childLocalName = child.getQName().getLocalName();
204 if (dataChildQNname == null) {
205 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
206 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
207 realChilds.add(dataSchemaNode);
208 childNames.add(dataSchemaNode.getQName());
212 realChilds.add(dataChildQNname);
213 childNames.add(child.getQName());
217 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
218 final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
219 return new SimpleEntry<>(identifier, proxy);
224 * Returns resolved case schema for supplied class
226 * @param schema Resolved parent choice schema
227 * @param childClass Class representing case.
228 * @return Optionally a resolved case schema, absent if the choice is not legal in
230 * @throws IllegalArgumentException If supplied class does not represent case.
232 public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
233 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
234 checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
236 /* FIXME: Make sure that if there are multiple augmentations of same
237 * named case, with same structure we treat it as equals
238 * this is due property of Binding specification and copy builders
239 * that user may be unaware that he is using incorrect case
240 * which was generated for choice inside grouping.
242 final Optional<CaseSchemaNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
243 (CaseSchemaNode) origSchema);
247 private static Type referencedType(final Class<?> type) {
248 return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
251 static Type referencedType(final String type) {
252 final int packageClassSeparator = type.lastIndexOf(DOT);
253 return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), type.substring(packageClassSeparator + 1));
257 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
258 * from which supplied class was generated. Returned schema may be augmented with
259 * additional information, which was not available at compile type
260 * (e.g. third party augmentations).
262 * @param type Binding Class for which schema should be retrieved.
263 * @return Instance of generated type (definition of Java API), along with
264 * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
265 * which was used to generate supplied class.
267 public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
268 return getTypeWithSchema(referencedType(type));
271 public Entry<GeneratedType, WithStatus> getTypeWithSchema(final String type) {
272 return getTypeWithSchema(referencedType(type));
275 private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
276 final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
277 () -> new NullPointerException("Failed to find schema for type " + referencedType));
278 final Type definedType = runtimeTypes.findType(schema).orElseThrow(
279 () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
281 if (definedType instanceof GeneratedTypeBuilder) {
282 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
284 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
285 return new SimpleEntry<>((GeneratedType) definedType, schema);
288 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
289 final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
291 for (final ChoiceSchemaNode choice : Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
292 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
293 final java.util.Optional<Type> optType = runtimeTypes.findType(originalChoice);
294 checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
295 final Type choiceType = optType.get();
297 for (Type caze : runtimeTypes.findCases(referencedType(choiceType))) {
298 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
299 final HashSet<Type> caseChildren = new HashSet<>();
300 if (caze instanceof GeneratedTypeBuilder) {
301 caze = ((GeneratedTypeBuilder) caze).build();
303 collectAllContainerTypes((GeneratedType) caze, caseChildren);
304 for (final Type caseChild : caseChildren) {
305 childToCase.put(caseChild, caseIdentifier);
309 return ImmutableMap.copyOf(childToCase);
313 * Map enum constants: yang - java
315 * @param enumClass enum generated class
316 * @return mapped enum constants from yang with their corresponding values in generated binding classes
318 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
319 final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
320 return getEnumMapping(typeWithSchema);
324 * See {@link #getEnumMapping(Class)}}
326 public BiMap<String, String> getEnumMapping(final String enumClass) {
327 final Entry<GeneratedType, WithStatus> typeWithSchema = getTypeWithSchema(enumClass);
328 return getEnumMapping(typeWithSchema);
331 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, WithStatus> typeWithSchema) {
332 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
334 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
335 final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
337 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
339 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
340 mappedEnums.put(enumPair.getName(), BindingMapping.getClassName(enumPair.getName()));
343 // TODO cache these maps for future use
347 public Set<Class<?>> getCases(final Class<?> choice) {
348 final Collection<Type> cazes = runtimeTypes.findCases(referencedType(choice));
349 final Set<Class<?>> ret = new HashSet<>(cazes.size());
350 for(final Type caze : cazes) {
352 final Class<?> c = strategy.loadClass(caze);
354 } catch (final ClassNotFoundException e) {
355 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
361 public Class<?> getClassForSchema(final SchemaNode childSchema) {
362 final SchemaNode origSchema = getOriginalSchema(childSchema);
363 final java.util.Optional<Type> clazzType = runtimeTypes.findType(origSchema);
364 checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
365 childSchema, origSchema);
368 return strategy.loadClass(clazzType.get());
369 } catch (final ClassNotFoundException e) {
370 throw new IllegalStateException(e);
374 public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
375 final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
376 if (container instanceof AugmentationTarget) {
377 final Set<AugmentationSchemaNode> augments = ((AugmentationTarget) container).getAvailableAugmentations();
378 for (final AugmentationSchemaNode augment : augments) {
379 // Augmentation must have child nodes if is to be used with Binding classes
380 AugmentationSchemaNode augOrig = augment;
381 while (augOrig.getOriginalDefinition().isPresent()) {
382 augOrig = augOrig.getOriginalDefinition().get();
385 if (!augment.getChildNodes().isEmpty()) {
386 final java.util.Optional<Type> augType = runtimeTypes.findType(augOrig);
387 if (augType.isPresent()) {
388 identifierToType.put(getAugmentationIdentifier(augment), augType.get());
394 return ImmutableMap.copyOf(identifierToType);
397 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
398 final Set<QName> childNames = new HashSet<>();
399 for (final DataSchemaNode child : augment.getChildNodes()) {
400 childNames.add(child.getQName());
402 return new AugmentationIdentifier(childNames);
405 private static Type referencedType(final Type type) {
406 if (type instanceof ReferencedTypeImpl) {
409 return new ReferencedTypeImpl(type.getPackageName(), type.getName());
412 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
413 for (final MethodSignature definition : type.getMethodDefinitions()) {
414 Type childType = definition.getReturnType();
415 if (childType instanceof ParameterizedType) {
416 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
418 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
419 collection.add(referencedType(childType));
422 for (final Type parent : type.getImplements()) {
423 if (parent instanceof GeneratedType) {
424 collectAllContainerTypes((GeneratedType) parent, collection);
430 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
431 @SuppressWarnings("unchecked")
432 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
433 if (original != null) {
439 public Class<?> getIdentityClass(final QName input) {
440 return identityClasses.getUnchecked(input);