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.generator.impl.util;
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.spec.structural.Augmentation;
42 import org.opendaylight.mdsal.binding.javav2.spec.util.BindingReflections;
43 import org.opendaylight.yangtools.concepts.Immutable;
44 import org.opendaylight.yangtools.yang.common.QName;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
48 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
49 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
51 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
52 import org.opendaylight.yangtools.yang.model.api.Module;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
56 import org.opendaylight.yangtools.yang.model.api.type.EnumTypeDefinition;
57 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
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, binding
67 * classes and underlying YANG schema, it contains runtime information, which
68 * could not be derived from generated classes alone using
69 * {@link BindingReflections}.
71 * Some of this information are for example list of all available children for
72 * cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are
73 * augmentable and new choices may be introduced by additional models.
75 * Same goes for all possible augmentations.
79 public class BindingRuntimeContext implements Immutable {
80 private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
81 private static final char DOT = '.';
82 private final ClassLoadingStrategy strategy;
83 private final SchemaContext schemaContext;
85 private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
86 private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.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 = BindingRuntimeContext.this.identities.get(key);
95 Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
97 return BindingRuntimeContext.this.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 final Map<Module, ModuleContext> modules = generator.getModuleContexts(this.schemaContext);
111 for (final ModuleContext ctx : modules.values()) {
112 this.augmentationToSchema.putAll(ctx.getTypeToAugmentation());
113 this.typeToDefiningSchema.putAll(ctx.getTypeToSchema());
116 this.choiceToCases.putAll(ctx.getChoiceToCases());
117 this.identities.putAll(ctx.getIdentities());
122 * Creates Binding Runtime Context from supplied class loading strategy and
126 * - class loading strategy to retrieve generated Binding classes
128 * - schema context which describes YANG model and to which
129 * Binding classes should be mapped
130 * @return Instance of BindingRuntimeContext for supplied schema context.
132 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
133 return new BindingRuntimeContext(strategy, ctx);
137 * Returns a class loading strategy associated with this binding runtime context
138 * which is used to load classes.
140 * @return Class loading strategy.
142 public ClassLoadingStrategy getStrategy() {
143 return this.strategy;
147 * Returns an stable immutable view of schema context associated with this Binding runtime context.
149 * @return stable view of schema context
151 public SchemaContext getSchemaContext() {
152 return this.schemaContext;
156 * Returns schema of augmentation
158 * Returned schema is schema definition from which augmentation class was
159 * generated. This schema is isolated from other augmentations. This means
160 * it contains augmentation definition as was present in original YANG
163 * Children of returned schema does not contain any additional
164 * augmentations, which may be present in runtime for them, thus returned
165 * schema is unsuitable for use for validation of data.
167 * For retrieving {@link AugmentationSchema}, which will contains full model
168 * for child nodes, you should use method
169 * {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)} which
170 * will return augmentation schema derived from supplied augmentation target
174 * - ugmentation class
175 * @return Schema of augmentation or null if augmentaiton is not known in
177 * @throws IllegalArgumentException
178 * - if supplied class is not an augmentation
180 public @Nullable AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
181 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
182 return this.augmentationToSchema.get(referencedType(augClass));
186 * Returns defining {@link DataSchemaNode} for supplied class.
189 * Returned schema is schema definition from which class was generated. This
190 * schema may be isolated from augmentations, if supplied class represent
191 * node, which was child of grouping or augmentation.
193 * For getting augmentation schema from augmentation class use
194 * {@link #getAugmentationDefinition(Class)} instead.
197 * - class which represents list, container, choice or case.
198 * @return Schema node, from which class was generated.
200 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
201 Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
202 return (DataSchemaNode) this.typeToDefiningSchema.get(referencedType(cls));
206 * Returns defining {@link AugmentationSchema} of target for supplied class.
209 * - {@link DataNodeContainer}
212 * @return entry of {@link AugmentationSchema} according to its identifier
213 * {@link AugmentationIdentifier}
215 public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
216 final Class<? extends Augmentation<?>> aug) {
217 final AugmentationSchema origSchema = getAugmentationDefinition(aug);
218 Preconditions.checkArgument(origSchema != null, "Augmentation %s is not known in current schema context",aug);
220 * FIXME: Validate augmentation schema lookup
222 * Currently this algorithm, does not verify if instantiated child nodes
223 * are real one derived from augmentation schema. The problem with full
224 * validation is, if user used copy builders, he may use augmentation
225 * which was generated for different place.
227 * If this augmentations have same definition, we emit same identifier
228 * with data and it is up to underlying user to validate data.
231 final Set<QName> childNames = new HashSet<>();
232 final Set<DataSchemaNode> realChilds = new HashSet<>();
233 for (final DataSchemaNode child : origSchema.getChildNodes()) {
234 final DataSchemaNode dataChildQNname = target.getDataChildByName(child.getQName());
235 final String childLocalName = child.getQName().getLocalName();
236 if (dataChildQNname == null) {
237 for (final DataSchemaNode dataSchemaNode : target.getChildNodes()) {
238 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
239 realChilds.add(dataSchemaNode);
240 childNames.add(dataSchemaNode.getQName());
244 realChilds.add(dataChildQNname);
245 childNames.add(child.getQName());
249 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
250 final AugmentationSchema proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
251 return new SimpleEntry<>(identifier, proxy);
255 * Returns resolved case schema for supplied class
258 * - resolved parent choice schema
260 * - class representing case.
261 * @return Optionally a resolved case schema, absent if the choice is not
262 * legal in the given context.
263 * @throws IllegalArgumentException
264 * - if supplied class does not represent case
266 public Optional<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
267 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
268 Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "Supplied schema %s is not case.", origSchema);
271 * FIXME: Make sure that if there are multiple augmentations of same
272 * named case, with same structure we treat it as equals this is due
273 * property of Binding specification and copy builders that user may be
274 * unaware that he is using incorrect case which was generated for
275 * choice inside grouping.
277 final Optional<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
278 (ChoiceCaseNode) origSchema);
282 private static Type referencedType(final Class<?> type) {
283 return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
286 static Type referencedType(final String type) {
287 final int packageClassSeparator = type.lastIndexOf(DOT);
288 return new ReferencedTypeImpl(type.substring(0, packageClassSeparator), type.substring(packageClassSeparator + 1));
292 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
293 * from which supplied class was generated. Returned schema may be augmented with
294 * additional information, which was not available at compile type
295 * (e.g. third party augmentations).
297 * @param type Binding Class for which schema should be retrieved.
298 * @return Instance of generated type (definition of Java API), along with
299 * {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
300 * which was used to generate supplied class.
302 public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
303 return getTypeWithSchema(referencedType(type));
306 public Entry<GeneratedType, Object> getTypeWithSchema(final String type) {
307 return getTypeWithSchema(referencedType(type));
310 private Entry<GeneratedType, Object> getTypeWithSchema(final Type referencedType) {
311 final Object schema = this.typeToDefiningSchema.get(referencedType);
312 Preconditions.checkNotNull(schema, "Failed to find schema for type %s", referencedType);
314 final Type definedType = this.typeToDefiningSchema.inverse().get(schema);
315 Preconditions.checkNotNull(definedType, "Failed to find defined type for %s schema %s", referencedType, schema);
317 if (definedType instanceof GeneratedTypeBuilder) {
318 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
320 Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType", referencedType);
321 return new SimpleEntry<>((GeneratedType) definedType,schema);
324 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
325 final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();
326 for (final ChoiceSchemaNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
327 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
328 final Type choiceType = referencedType(this.typeToDefiningSchema.inverse().get(originalChoice));
329 final Collection<Type> cases = this.choiceToCases.get(choiceType);
331 for (Type caze : cases) {
332 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
333 final HashSet<Type> caseChildren = new HashSet<>();
334 if (caze instanceof GeneratedTypeBuilder) {
335 caze = ((GeneratedTypeBuilder) caze).toInstance();
337 collectAllContainerTypes((GeneratedType) caze, caseChildren);
338 for (final Type caseChild : caseChildren) {
339 childToCase.put(caseChild, caseIdentifier);
343 return ImmutableMap.copyOf(childToCase);
347 * Map enum constants: yang - java
349 * @param enumClass enum generated class
350 * @return mapped enum constants from yang with their corresponding values in generated binding classes
352 public BiMap<String, String> getEnumMapping(final Class<?> enumClass) {
353 final Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
354 return getEnumMapping(typeWithSchema);
358 * See {@link #getEnumMapping(Class)}}
360 public BiMap<String, String> getEnumMapping(final String enumClass) {
361 final Entry<GeneratedType, Object> typeWithSchema = getTypeWithSchema(enumClass);
362 return getEnumMapping(typeWithSchema);
365 private static BiMap<String, String> getEnumMapping(final Entry<GeneratedType, Object> typeWithSchema) {
366 final TypeDefinition<?> typeDef = (TypeDefinition<?>) typeWithSchema.getValue();
368 Preconditions.checkArgument(typeDef instanceof EnumTypeDefinition);
369 final EnumTypeDefinition enumType = (EnumTypeDefinition) typeDef;
371 final HashBiMap<String, String> mappedEnums = HashBiMap.create();
373 for (final EnumTypeDefinition.EnumPair enumPair : enumType.getValues()) {
374 mappedEnums.put(enumPair.getName(),
375 JavaIdentifierNormalizer.normalizeSpecificIdentifier(enumPair.getName(), JavaIdentifier.CLASS));
378 // TODO cache these maps for future use
383 public Set<Class<?>> getCases(final Class<?> choice) {
384 final Collection<Type> cazes = this.choiceToCases.get(referencedType(choice));
385 final Set<Class<?>> ret = new HashSet<>(cazes.size());
386 for(final Type caze : cazes) {
388 final Class<?> c = this.strategy.loadClass(caze);
390 } catch (final ClassNotFoundException e) {
391 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
397 public Class<?> getClassForSchema(final SchemaNode childSchema) {
398 final SchemaNode origSchema = getOriginalSchema(childSchema);
399 final Type clazzType = this.typeToDefiningSchema.inverse().get(origSchema);
401 return this.strategy.loadClass(clazzType);
402 } catch (final ClassNotFoundException e) {
403 throw new IllegalStateException(e);
407 public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
408 final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
409 if (container instanceof AugmentationTarget) {
410 final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
411 for (final AugmentationSchema augment : augments) {
412 // Augmentation must have child nodes if is to be used with Binding classes
413 AugmentationSchema augOrig = augment;
414 while (augOrig.getOriginalDefinition().isPresent()) {
415 augOrig = augOrig.getOriginalDefinition().get();
418 if (!augment.getChildNodes().isEmpty()) {
419 final Type augType = this.typeToDefiningSchema.inverse().get(augOrig);
420 if (augType != null) {
421 identifierToType.put(getAugmentationIdentifier(augment),augType);
427 return ImmutableMap.copyOf(identifierToType);
430 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
431 final Set<QName> childNames = new HashSet<>();
432 for (final DataSchemaNode child : augment.getChildNodes()) {
433 childNames.add(child.getQName());
435 return new AugmentationIdentifier(childNames);
438 private static Type referencedType(final Type type) {
439 if (type instanceof ReferencedTypeImpl) {
442 return new ReferencedTypeImpl(type.getPackageName(), type.getName());
445 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
446 for (final MethodSignature definition : type.getMethodDefinitions()) {
447 Type childType = definition.getReturnType();
448 if (childType instanceof ParameterizedType) {
449 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
451 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
452 collection.add(referencedType(childType));
455 for (final Type parent : type.getImplements()) {
456 if (parent instanceof GeneratedType) {
457 collectAllContainerTypes((GeneratedType) parent, collection);
463 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
464 @SuppressWarnings("unchecked")
465 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
466 if (original != null) {
472 public Class<?> getIdentityClass(final QName input) {
473 return this.identityClasses.getUnchecked(input);