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.runtime.api;
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
13 import com.google.common.annotations.Beta;
14 import com.google.common.cache.CacheBuilder;
15 import com.google.common.cache.CacheLoader;
16 import com.google.common.cache.LoadingCache;
17 import com.google.common.collect.ImmutableMap;
18 import com.google.common.collect.ImmutableSet;
19 import com.google.common.collect.Iterables;
20 import java.util.AbstractMap.SimpleEntry;
21 import java.util.Collection;
22 import java.util.HashMap;
23 import java.util.HashSet;
25 import java.util.Map.Entry;
26 import java.util.Optional;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.eclipse.jdt.annotation.Nullable;
30 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
31 import org.opendaylight.mdsal.binding.model.api.MethodSignature;
32 import org.opendaylight.mdsal.binding.model.api.ParameterizedType;
33 import org.opendaylight.mdsal.binding.model.api.Type;
34 import org.opendaylight.mdsal.binding.model.api.type.builder.GeneratedTypeBuilder;
35 import org.opendaylight.yangtools.yang.binding.Action;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.common.QName;
38 import org.opendaylight.yangtools.yang.common.QNameModule;
39 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
40 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
41 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
42 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
43 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
45 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
46 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
49 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
50 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
51 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
52 import org.slf4j.Logger;
53 import org.slf4j.LoggerFactory;
56 * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
57 * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
59 * <p>Some of this information are for example list of all available children for cases
60 * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
61 * by additional models. Same goes for all possible augmentations.
64 public abstract class AbstractBindingRuntimeContext implements BindingRuntimeContext {
65 private static final Logger LOG = LoggerFactory.getLogger(AbstractBindingRuntimeContext.class);
67 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
68 new CacheLoader<QName, Class<?>>() {
70 public Class<?> load(final QName key) {
71 final Optional<Type> identityType = getTypes().findIdentity(key);
72 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
74 return loadClass(identityType.get());
75 } catch (final ClassNotFoundException e) {
76 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
82 public final <T extends Augmentation<?>> AugmentationSchemaNode getAugmentationDefinition(final Class<T> augClass) {
83 return getTypes().findAugmentation(Type.of(augClass)).orElse(null);
87 public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
88 checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
90 checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
91 return (DataSchemaNode) getTypes().findSchema(Type.of(cls)).orElse(null);
95 public final DataSchemaNode findChildSchemaDefinition(final DataNodeContainer parentSchema,
96 final QNameModule parentNamespace, final Class<?> childClass) {
97 final DataSchemaNode origDef = getSchemaDefinition(childClass);
98 if (origDef == null) {
99 // Weird, the child does not have an associated definition
103 // Direct instantiation or use in same module in which grouping was defined.
104 final QName origName = origDef.getQName();
105 final DataSchemaNode sameName = parentSchema.dataChildByName(origName);
106 if (sameName != null) {
108 // - exactly same schema node, or
109 // - instantiated node was added via uses statement and is instantiation of same grouping
110 if (origDef.equals(sameName) || origDef.equals(getRootOriginalIfPossible(sameName))) {
114 // Node has same name, but clearly is different
118 // We are looking for instantiation via uses in other module
119 final DataSchemaNode potential = parentSchema.dataChildByName(origName.bindTo(parentNamespace));
120 // We check if it is really instantiated from same definition as class was derived
121 if (potential != null && origDef.equals(getRootOriginalIfPossible(potential))) {
127 private static @Nullable SchemaNode getRootOriginalIfPossible(final SchemaNode data) {
128 SchemaNode previous = null;
129 SchemaNode next = originalNodeOf(data);
130 while (next != null) {
132 next = originalNodeOf(next);
138 public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
139 return (ActionDefinition) getTypes().findSchema(Type.of(cls)).orElse(null);
143 public final Absolute getActionIdentifier(final Class<? extends Action<?, ?, ?>> cls) {
144 return getTypes().findSchemaNodeIdentifier(Type.of(cls)).orElse(null);
148 public final Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
149 final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
150 final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
151 checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
153 * FIXME: Validate augmentation schema lookup
155 * Currently this algorithm, does not verify if instantiated child nodes
156 * are real one derived from augmentation schema. The problem with
157 * full validation is, if user used copy builders, he may use
158 * augmentation which was generated for different place.
160 * If this augmentations have same definition, we emit same identifier
161 * with data and it is up to underlying user to validate data.
164 final Set<QName> childNames = new HashSet<>();
165 final Set<DataSchemaNode> realChilds = new HashSet<>();
166 for (final DataSchemaNode child : origSchema.getChildNodes()) {
167 final DataSchemaNode dataChildQNname = target.dataChildByName(child.getQName());
168 final String childLocalName = child.getQName().getLocalName();
169 if (dataChildQNname == null) {
170 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
171 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
172 realChilds.add(dataSchemaNode);
173 childNames.add(dataSchemaNode.getQName());
177 realChilds.add(dataChildQNname);
178 childNames.add(child.getQName());
182 final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
183 final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
184 return new SimpleEntry<>(identifier, proxy);
188 public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
189 final Class<?> childClass) {
190 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
191 checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
193 /* FIXME: Make sure that if there are multiple augmentations of same
194 * named case, with same structure we treat it as equals
195 * this is due property of Binding specification and copy builders
196 * that user may be unaware that he is using incorrect case
197 * which was generated for choice inside grouping.
199 return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
203 public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
204 return getTypeWithSchema(getTypes(), Type.of(type));
207 private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
208 final Type referencedType) {
209 final WithStatus schema = types.findSchema(referencedType).orElseThrow(
210 () -> new NullPointerException("Failed to find schema for type " + referencedType));
211 final Type definedType = types.findType(schema).orElseThrow(
212 () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
214 if (definedType instanceof GeneratedTypeBuilder) {
215 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
217 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
218 return new SimpleEntry<>((GeneratedType) definedType, schema);
222 public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
223 return getChoiceCaseChildren(getTypes(), schema);
226 private static @NonNull ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final BindingRuntimeTypes types,
227 final DataNodeContainer schema) {
228 final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
230 for (final ChoiceSchemaNode choice : Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
231 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
232 final Optional<Type> optType = types.findType(originalChoice);
233 checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
234 final Type choiceType = optType.get();
236 for (Type caze : types.findCases(choiceType)) {
237 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
238 final HashSet<Type> caseChildren = new HashSet<>();
239 if (caze instanceof GeneratedTypeBuilder) {
240 caze = ((GeneratedTypeBuilder) caze).build();
242 collectAllContainerTypes((GeneratedType) caze, caseChildren);
243 for (final Type caseChild : caseChildren) {
244 childToCase.put(caseChild, caseIdentifier);
248 return ImmutableMap.copyOf(childToCase);
252 public final Set<Class<?>> getCases(final Class<?> choice) {
253 final Collection<Type> cazes = getTypes().findCases(Type.of(choice));
254 final Set<Class<?>> ret = new HashSet<>(cazes.size());
255 for (final Type caze : cazes) {
257 ret.add(loadClass(caze));
258 } catch (final ClassNotFoundException e) {
259 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
266 public final Class<?> getClassForSchema(final SchemaNode childSchema) {
267 final SchemaNode origSchema = getOriginalSchema(childSchema);
268 final Optional<Type> clazzType = getTypes().findType(origSchema);
269 checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
270 childSchema, origSchema);
273 return loadClass(clazzType.get());
274 } catch (final ClassNotFoundException e) {
275 throw new IllegalStateException(e);
280 public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
281 final DataNodeContainer container) {
282 if (container instanceof AugmentationTarget) {
283 final var augmentations = ((AugmentationTarget) container).getAvailableAugmentations();
284 if (!augmentations.isEmpty()) {
285 final var identifierToType = new HashMap<AugmentationIdentifier, Type>();
286 final var types = getTypes();
287 for (var augment : augmentations) {
288 types.findOriginalAugmentationType(augment).ifPresent(augType -> {
289 identifierToType.put(getAugmentationIdentifier(augment), augType);
292 return ImmutableMap.copyOf(identifierToType);
295 return ImmutableMap.of();
299 public final Class<?> getIdentityClass(final QName input) {
300 return identityClasses.getUnchecked(input);
303 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
304 // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
305 return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
306 .collect(ImmutableSet.toImmutableSet()));
309 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
310 for (final MethodSignature definition : type.getMethodDefinitions()) {
311 Type childType = definition.getReturnType();
312 if (childType instanceof ParameterizedType) {
313 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
315 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
316 collection.add(childType);
319 for (final Type parent : type.getImplements()) {
320 if (parent instanceof GeneratedType) {
321 collectAllContainerTypes((GeneratedType) parent, collection);
327 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
328 @SuppressWarnings("unchecked")
329 final T original = (T) originalNodeOf(choice);
330 if (original != null) {
336 private static @NonNull Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
337 final CaseSchemaNode originalDefinition) {
338 CaseSchemaNode potential = instantiatedChoice.findCase(originalDefinition.getQName()).orElse(null);
339 if (originalDefinition.equals(potential)) {
340 return Optional.of(potential);
342 if (potential != null) {
343 SchemaNode potentialRoot = originalNodeOf(potential);
344 if (originalDefinition.equals(potentialRoot)) {
345 return Optional.of(potential);
349 // We try to find case by name, then lookup its root definition
350 // and compare it with original definition
351 // This solves case, if choice was inside grouping
352 // which was used in different module and thus namespaces are
353 // different, but local names are still same.
355 // Still we need to check equality of definition, because local name is not
356 // sufficient to uniquelly determine equality of cases
358 for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
359 if (originalDefinition.equals(originalNodeOf(caze))) {
360 return Optional.of(caze);
363 return Optional.empty();
366 private static @Nullable SchemaNode originalNodeOf(final SchemaNode node) {
367 return node instanceof DerivableSchemaNode ? ((DerivableSchemaNode) node).getOriginal().orElse(null) : null;