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 org.opendaylight.yangtools.binding.generator.util.ReferencedTypeImpl;
30 import org.opendaylight.yangtools.concepts.Immutable;
31 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
32 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingGeneratorImpl;
33 import org.opendaylight.yangtools.sal.binding.generator.impl.BindingSchemaContextUtils;
34 import org.opendaylight.yangtools.sal.binding.generator.impl.ModuleContext;
35 import org.opendaylight.yangtools.sal.binding.model.api.GeneratedType;
36 import org.opendaylight.yangtools.sal.binding.model.api.MethodSignature;
37 import org.opendaylight.yangtools.sal.binding.model.api.ParameterizedType;
38 import org.opendaylight.yangtools.sal.binding.model.api.Type;
39 import org.opendaylight.yangtools.sal.binding.model.api.type.builder.GeneratedTypeBuilder;
40 import org.opendaylight.yangtools.yang.binding.Augmentation;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
43 import org.opendaylight.yangtools.yang.data.impl.schema.transform.base.AugmentationSchemaProxy;
44 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
45 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
46 import org.opendaylight.yangtools.yang.model.api.ChoiceCaseNode;
47 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
49 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.Module;
51 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
52 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
54 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
55 import org.slf4j.Logger;
56 import org.slf4j.LoggerFactory;
59 * Runtime Context for Java YANG Binding classes
62 * Runtime Context provides additional insight in Java YANG Binding,
63 * binding classes and underlying YANG schema, it contains
64 * runtime information, which could not be derived from generated
65 * classes alone using {@link org.opendaylight.yangtools.yang.binding.util.BindingReflections}.
67 * Some of this information are for example list of all available
68 * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
69 * choices are augmentable and new choices may be introduced by additional models.
71 * Same goes for all possible augmentations.
74 public class BindingRuntimeContext implements Immutable {
75 private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
76 private final ClassLoadingStrategy strategy;
77 private final SchemaContext schemaContext;
79 private final Map<Type, AugmentationSchema> augmentationToSchema = new HashMap<>();
80 private final BiMap<Type, Object> typeToDefiningSchema = HashBiMap.create();
81 private final Multimap<Type, Type> augmentableToAugmentations = HashMultimap.create();
82 private final Multimap<Type, Type> choiceToCases = HashMultimap.create();
83 private final Map<QName, Type> identities = new HashMap<>();
85 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
86 new CacheLoader<QName, Class<?>>() {
88 public Class<?> load(final QName key) {
89 final Type identityType = identities.get(key);
90 Preconditions.checkArgument(identityType != null, "Supplied QName %s is not a valid identity", key);
92 return strategy.loadClass(identityType);
93 } catch (final ClassNotFoundException e) {
94 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
99 private BindingRuntimeContext(final ClassLoadingStrategy strategy, final SchemaContext schema) {
100 this.strategy = strategy;
101 this.schemaContext = schema;
103 final BindingGeneratorImpl generator = new BindingGeneratorImpl(false);
104 generator.generateTypes(schema);
105 final Map<Module, ModuleContext> modules = generator.getModuleContexts();
107 for (final ModuleContext ctx : modules.values()) {
108 augmentationToSchema.putAll(ctx.getTypeToAugmentation());
109 typeToDefiningSchema.putAll(ctx.getTypeToSchema());
112 augmentableToAugmentations.putAll(ctx.getAugmentableToAugmentations());
113 choiceToCases.putAll(ctx.getChoiceToCases());
114 identities.putAll(ctx.getIdentities());
120 * Creates Binding Runtime Context from supplied class loading strategy and schema context.
122 * @param strategy Class loading strategy to retrieve generated Binding classes
123 * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
124 * @return Instance of BindingRuntimeContext for supplied schema context.
126 public static final BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
127 return new BindingRuntimeContext(strategy, ctx);
131 * Returns a class loading strategy associated with this binding runtime context
132 * which is used to load classes.
134 * @return Class loading strategy.
136 public ClassLoadingStrategy getStrategy() {
141 * Returns an stable immutable view of schema context associated with this Binding runtime context.
143 * @return stable view of schema context
145 public SchemaContext getSchemaContext() {
146 return schemaContext;
150 * Returns schema of augmentation
152 * Returned schema is schema definition from which augmentation class was generated.
153 * This schema is isolated from other augmentations. This means it contains
154 * augmentation definition as was present in original YANG module.
156 * Children of returned schema does not contain any additional augmentations,
157 * which may be present in runtime for them, thus returned schema is unsuitable
158 * for use for validation of data.
160 * For retrieving {@link AugmentationSchema}, which will contains
161 * full model for child nodes, you should use method {@link #getResolvedAugmentationSchema(DataNodeContainer, Class)}
162 * which will return augmentation schema derived from supplied augmentation target
165 * @param augClass Augmentation class
166 * @return Schema of augmentation
167 * @throws IllegalArgumentException If supplied class is not an augmentation or current context does not contain schema for augmentation.
169 public AugmentationSchema getAugmentationDefinition(final Class<?> augClass) throws IllegalArgumentException {
170 Preconditions.checkArgument(Augmentation.class.isAssignableFrom(augClass), "Class %s does not represent augmentation", augClass);
171 final AugmentationSchema ret = augmentationToSchema.get(referencedType(augClass));
172 Preconditions.checkArgument(ret != null, "Supplied augmentation %s is not valid in current context", augClass);
177 * Returns defining {@link DataSchemaNode} for supplied class.
180 * Returned schema is schema definition from which class was generated.
181 * This schema may be isolated from augmentations, if supplied class
182 * represent node, which was child of grouping or augmentation.
184 * For getting augmentation schema from augmentation class use
185 * {@link #getAugmentationDefinition(Class)} instead.
187 * @param cls Class which represents list, container, choice or case.
188 * @return Schema node, from which class was generated.
190 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
191 Preconditions.checkArgument(!Augmentation.class.isAssignableFrom(cls),"Supplied class must not be augmentation (%s is)", cls);
192 return (DataSchemaNode) typeToDefiningSchema.get(referencedType(cls));
195 public Entry<AugmentationIdentifier, AugmentationSchema> getResolvedAugmentationSchema(final DataNodeContainer target,
196 final Class<? extends Augmentation<?>> aug) {
197 final AugmentationSchema origSchema = getAugmentationDefinition(aug);
199 * FIXME: Validate augmentation schema lookup
201 * Currently this algorithm, does not verify if instantiated child nodes
202 * are real one derived from augmentation schema. The problem with
203 * full validation is, if user used copy builders, he may use
204 * augmentation which was generated for different place.
206 * If this augmentations have same definition, we emit same identifier
207 * with data and it is up to underlying user to validate data.
210 final Set<QName> childNames = new HashSet<>();
211 final Set<DataSchemaNode> realChilds = new HashSet<>();
212 for (final DataSchemaNode child : origSchema.getChildNodes()) {
213 realChilds.add(target.getDataChildByName(child.getQName()));
214 childNames.add(child.getQName());
217 final AugmentationIdentifier identifier = new AugmentationIdentifier(childNames);
218 final AugmentationSchema proxy = new AugmentationSchemaProxy(origSchema, realChilds);
219 return new AbstractMap.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<ChoiceCaseNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) throws IllegalArgumentException {
233 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
234 Preconditions.checkArgument(origSchema instanceof ChoiceCaseNode, "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<ChoiceCaseNode> found = BindingSchemaContextUtils.findInstantiatedCase(schema,
243 (ChoiceCaseNode) origSchema);
247 private static Type referencedType(final Class<?> type) {
248 return new ReferencedTypeImpl(type.getPackage().getName(), type.getSimpleName());
252 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition})
253 * from which supplied class was generated. Returned schema may be augmented with
254 * additional information, which was not available at compile type
255 * (e.g. third party augmentations).
257 * @param type Binding Class for which schema should be retrieved.
258 * @return Instance of generated type (definition of Java API), along with
259 * {@link DataSchemaNode}, {@link AugmentationSchema} or {@link TypeDefinition}
260 * which was used to generate supplied class.
262 public Entry<GeneratedType, Object> getTypeWithSchema(final Class<?> type) {
263 final Object schema = typeToDefiningSchema.get(referencedType(type));
264 final Type definedType = typeToDefiningSchema.inverse().get(schema);
265 Preconditions.checkNotNull(schema);
266 Preconditions.checkNotNull(definedType);
267 if(definedType instanceof GeneratedTypeBuilder) {
268 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).toInstance(), schema);
270 Preconditions.checkArgument(definedType instanceof GeneratedType,"Type {} is not GeneratedType",type);
271 return new SimpleEntry<>((GeneratedType) definedType,schema);
275 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
276 final Map<Type,Entry<Type,Type>> childToCase = new HashMap<>();;
277 for (final ChoiceSchemaNode choice : FluentIterable.from(schema.getChildNodes()).filter(ChoiceSchemaNode.class)) {
278 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
279 final Type choiceType = referencedType(typeToDefiningSchema.inverse().get(originalChoice));
280 final Collection<Type> cases = choiceToCases.get(choiceType);
282 for (Type caze : cases) {
283 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType,caze);
284 final HashSet<Type> caseChildren = new HashSet<>();
285 if (caze instanceof GeneratedTypeBuilder) {
286 caze = ((GeneratedTypeBuilder) caze).toInstance();
288 collectAllContainerTypes((GeneratedType) caze, caseChildren);
289 for (final Type caseChild : caseChildren) {
290 childToCase.put(caseChild, caseIdentifier);
294 return ImmutableMap.copyOf(childToCase);
297 public Set<Class<?>> getCases(final Class<?> choice) {
298 final Collection<Type> cazes = choiceToCases.get(referencedType(choice));
299 final Set<Class<?>> ret = new HashSet<>(cazes.size());
300 for(final Type caze : cazes) {
302 final Class<?> c = strategy.loadClass(caze);
304 } catch (final ClassNotFoundException e) {
305 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
311 public Class<?> getClassForSchema(final SchemaNode childSchema) {
312 final SchemaNode origSchema = getOriginalSchema(childSchema);
313 final Type clazzType = typeToDefiningSchema.inverse().get(origSchema);
315 return strategy.loadClass(clazzType);
316 } catch (final ClassNotFoundException e) {
317 throw new IllegalStateException(e);
321 public ImmutableMap<AugmentationIdentifier,Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
322 final Map<AugmentationIdentifier,Type> identifierToType = new HashMap<>();
323 if (container instanceof AugmentationTarget) {
324 final Set<AugmentationSchema> augments = ((AugmentationTarget) container).getAvailableAugmentations();
325 for (final AugmentationSchema augment : augments) {
326 // Augmentation must have child nodes if is to be used with Binding classes
327 AugmentationSchema augOrig = augment;
328 while (augOrig.getOriginalDefinition().isPresent()) {
329 augOrig = augOrig.getOriginalDefinition().get();
332 if (!augment.getChildNodes().isEmpty()) {
333 final Type augType = typeToDefiningSchema.inverse().get(augOrig);
334 if (augType != null) {
335 identifierToType.put(getAugmentationIdentifier(augment),augType);
341 return ImmutableMap.copyOf(identifierToType);
344 private AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchema augment) {
345 final Set<QName> childNames = new HashSet<>();
346 for (final DataSchemaNode child : augment.getChildNodes()) {
347 childNames.add(child.getQName());
349 return new AugmentationIdentifier(childNames);
352 private static Type referencedType(final Type type) {
353 if(type instanceof ReferencedTypeImpl) {
356 return new ReferencedTypeImpl(type.getPackageName(), type.getName());
359 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
360 for (final MethodSignature definition : type.getMethodDefinitions()) {
361 Type childType = definition.getReturnType();
362 if(childType instanceof ParameterizedType) {
363 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
365 if(childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
366 collection.add(referencedType(childType));
369 for (final Type parent : type.getImplements()) {
370 if (parent instanceof GeneratedType) {
371 collectAllContainerTypes((GeneratedType) parent, collection);
377 private static final <T extends SchemaNode> T getOriginalSchema(final T choice) {
378 @SuppressWarnings("unchecked")
379 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
380 if (original != null) {
386 public Class<?> getIdentityClass(final QName input) {
387 return identityClasses.getUnchecked(input);