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;
12 import static java.util.Objects.requireNonNull;
14 import com.google.common.base.MoreObjects;
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.ImmutableMap;
19 import com.google.common.collect.ImmutableSet;
20 import com.google.common.collect.Iterables;
21 import java.util.AbstractMap.SimpleEntry;
22 import java.util.Collection;
23 import java.util.HashMap;
24 import java.util.HashSet;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.ServiceLoader;
30 import org.eclipse.jdt.annotation.Nullable;
31 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeGenerator;
32 import org.opendaylight.mdsal.binding.generator.api.BindingRuntimeTypes;
33 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
34 import org.opendaylight.mdsal.binding.model.api.DefaultType;
35 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
36 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
37 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
38 import org.opendaylight.mdsal.binding.model.api.Type;
39 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
40 import org.opendaylight.yangtools.concepts.Immutable;
41 import org.opendaylight.yangtools.yang.binding.Action;
42 import org.opendaylight.yangtools.yang.binding.Augmentation;
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.ActionDefinition;
46 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
48 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
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.DocumentedNode.WithStatus;
53 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
54 import org.opendaylight.yangtools.yang.model.api.SchemaContextProvider;
55 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
56 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
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
65 * <p>Runtime Context provides additional insight in Java YANG Binding,
66 * binding classes and underlying YANG schema, it contains
67 * runtime information, which could not be derived from generated
68 * classes alone using {@link org.opendaylight.mdsal.binding.spec.reflect.BindingReflections}.
70 * <p>Some of this information are for example list of all available
71 * children for cases {@link #getChoiceCaseChildren(DataNodeContainer)}, since
72 * choices are augmentable and new choices may be introduced by additional models.
74 * <p>Same goes for all possible augmentations.
76 public final class BindingRuntimeContext implements SchemaContextProvider, Immutable {
77 private static final Logger LOG = LoggerFactory.getLogger(BindingRuntimeContext.class);
78 private static final BindingRuntimeGenerator GENERATOR = ServiceLoader.load(BindingRuntimeGenerator.class)
80 .orElseThrow(() -> new IllegalStateException("No BindingRuntimeGenerator implementation found"));
83 private final BindingRuntimeTypes runtimeTypes;
84 private final ClassLoadingStrategy strategy;
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 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 BindingRuntimeTypes runtimeTypes, final ClassLoadingStrategy strategy) {
101 this.runtimeTypes = requireNonNull(runtimeTypes);
102 this.strategy = requireNonNull(strategy);
106 * Creates Binding Runtime Context from supplied class loading strategy and schema context.
108 * @param strategy Class loading strategy to retrieve generated Binding classes
109 * @param ctx Schema Context which describes YANG model and to which Binding classes should be mapped
110 * @return Instance of BindingRuntimeContext for supplied schema context.
112 public static BindingRuntimeContext create(final ClassLoadingStrategy strategy, final SchemaContext ctx) {
113 return new BindingRuntimeContext(GENERATOR.generateTypeMapping(ctx), strategy);
117 * Returns a class loading strategy associated with this binding runtime context
118 * which is used to load classes.
120 * @return Class loading strategy.
122 public ClassLoadingStrategy getStrategy() {
127 * Returns an stable immutable view of schema context associated with this Binding runtime context.
129 * @return stable view of schema context
132 public SchemaContext getSchemaContext() {
133 return runtimeTypes.getSchemaContext();
137 * Returns schema of augmentation.
139 * <p>Returned schema is schema definition from which augmentation class was generated.
140 * This schema is isolated from other augmentations. This means it contains
141 * augmentation definition as was present in original YANG module.
143 * <p>Children of returned schema does not contain any additional augmentations,
144 * which may be present in runtime for them, thus returned schema is unsuitable
145 * for use for validation of data.
147 * <p>For retrieving {@link AugmentationSchemaNode}, which will contains
148 * full model for child nodes, you should use method
149 * {@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(DefaultType.of(augClass)).orElse(null);
164 * Returns defining {@link DataSchemaNode} for supplied class.
166 * <p>Returned schema is schema definition from which class was generated.
167 * This schema may be isolated from augmentations, if supplied class
168 * represent node, which was child of grouping or augmentation.
170 * <p>For getting augmentation schema from augmentation class use
171 * {@link #getAugmentationDefinition(Class)} instead.
173 * @param cls Class which represents list, container, choice or case.
174 * @return Schema node, from which class was generated.
176 public DataSchemaNode getSchemaDefinition(final Class<?> cls) {
177 checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
179 checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
180 return (DataSchemaNode) runtimeTypes.findSchema(DefaultType.of(cls)).orElse(null);
183 public ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
184 return (ActionDefinition) runtimeTypes.findSchema(DefaultType.of(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 = AugmentationIdentifier.create(childNames);
222 final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
223 return new SimpleEntry<>(identifier, proxy);
227 * Returns resolved case schema for supplied class.
229 * @param schema Resolved parent choice schema
230 * @param childClass Class representing case.
231 * @return Optionally a resolved case schema,.empty if the choice is not legal in
233 * @throws IllegalArgumentException If supplied class does not represent case.
235 public Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema, final Class<?> childClass) {
236 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
237 checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
239 /* FIXME: Make sure that if there are multiple augmentations of same
240 * named case, with same structure we treat it as equals
241 * this is due property of Binding specification and copy builders
242 * that user may be unaware that he is using incorrect case
243 * which was generated for choice inside grouping.
245 final Optional<CaseSchemaNode> found = findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
250 * Returns schema ({@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition})
251 * from which supplied class was generated. Returned schema may be augmented with
252 * additional information, which was not available at compile type
253 * (e.g. third party augmentations).
255 * @param type Binding Class for which schema should be retrieved.
256 * @return Instance of generated type (definition of Java API), along with
257 * {@link DataSchemaNode}, {@link AugmentationSchemaNode} or {@link TypeDefinition}
258 * which was used to generate supplied class.
260 public Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
261 return getTypeWithSchema(DefaultType.of(type));
264 private Entry<GeneratedType, WithStatus> getTypeWithSchema(final Type referencedType) {
265 final WithStatus schema = runtimeTypes.findSchema(referencedType).orElseThrow(
266 () -> new NullPointerException("Failed to find schema for type " + referencedType));
267 final Type definedType = runtimeTypes.findType(schema).orElseThrow(
268 () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
270 if (definedType instanceof GeneratedTypeBuilder) {
271 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
273 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
274 return new SimpleEntry<>((GeneratedType) definedType, schema);
277 public ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
278 final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
280 for (final ChoiceSchemaNode choice : Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
281 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
282 final Optional<Type> optType = runtimeTypes.findType(originalChoice);
283 checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
284 final Type choiceType = optType.get();
286 for (Type caze : runtimeTypes.findCases(choiceType)) {
287 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
288 final HashSet<Type> caseChildren = new HashSet<>();
289 if (caze instanceof GeneratedTypeBuilder) {
290 caze = ((GeneratedTypeBuilder) caze).build();
292 collectAllContainerTypes((GeneratedType) caze, caseChildren);
293 for (final Type caseChild : caseChildren) {
294 childToCase.put(caseChild, caseIdentifier);
298 return ImmutableMap.copyOf(childToCase);
301 public Set<Class<?>> getCases(final Class<?> choice) {
302 final Collection<Type> cazes = runtimeTypes.findCases(DefaultType.of(choice));
303 final Set<Class<?>> ret = new HashSet<>(cazes.size());
304 for (final Type caze : cazes) {
306 final Class<?> c = strategy.loadClass(caze);
308 } catch (final ClassNotFoundException e) {
309 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
315 public Class<?> getClassForSchema(final SchemaNode childSchema) {
316 final SchemaNode origSchema = getOriginalSchema(childSchema);
317 final Optional<Type> clazzType = runtimeTypes.findType(origSchema);
318 checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
319 childSchema, origSchema);
322 return strategy.loadClass(clazzType.get());
323 } catch (final ClassNotFoundException e) {
324 throw new IllegalStateException(e);
328 public ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(final DataNodeContainer container) {
329 final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
330 if (container instanceof AugmentationTarget) {
331 for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
332 // Augmentation must have child nodes if is to be used with Binding classes
333 AugmentationSchemaNode augOrig = augment;
334 while (augOrig.getOriginalDefinition().isPresent()) {
335 augOrig = augOrig.getOriginalDefinition().get();
338 if (!augment.getChildNodes().isEmpty()) {
339 final Optional<Type> augType = runtimeTypes.findType(augOrig);
340 if (augType.isPresent()) {
341 identifierToType.put(getAugmentationIdentifier(augment), augType.get());
347 return ImmutableMap.copyOf(identifierToType);
350 public Class<?> getIdentityClass(final QName input) {
351 return identityClasses.getUnchecked(input);
355 public String toString() {
356 return MoreObjects.toStringHelper(this)
357 .add("ClassLoadingStrategy", strategy)
358 .add("runtimeTypes", runtimeTypes)
362 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
363 // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
364 return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
365 .collect(ImmutableSet.toImmutableSet()));
368 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
369 for (final MethodSignature definition : type.getMethodDefinitions()) {
370 Type childType = definition.getReturnType();
371 if (childType instanceof ParameterizedType) {
372 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
374 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
375 collection.add(childType);
378 for (final Type parent : type.getImplements()) {
379 if (parent instanceof GeneratedType) {
380 collectAllContainerTypes((GeneratedType) parent, collection);
386 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
387 @SuppressWarnings("unchecked")
388 final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
389 if (original != null) {
395 private static Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
396 final CaseSchemaNode originalDefinition) {
397 CaseSchemaNode potential = instantiatedChoice.getCaseNodeByName(originalDefinition.getQName());
398 if (originalDefinition.equals(potential)) {
399 return Optional.of(potential);
401 if (potential != null) {
402 SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
403 if (originalDefinition.equals(potentialRoot)) {
404 return Optional.of(potential);
408 // We try to find case by name, then lookup its root definition
409 // and compare it with original definition
410 // This solves case, if choice was inside grouping
411 // which was used in different module and thus namespaces are
412 // different, but local names are still same.
414 // Still we need to check equality of definition, because local name is not
415 // sufficient to uniquelly determine equality of cases
417 for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
418 if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
419 return Optional.of(caze);
422 return Optional.empty();