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.data.api.YangInstanceIdentifier.AugmentationIdentifier;
39 import org.opendaylight.yangtools.yang.model.api.ActionDefinition;
40 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
41 import org.opendaylight.yangtools.yang.model.api.AugmentationTarget;
42 import org.opendaylight.yangtools.yang.model.api.CaseSchemaNode;
43 import org.opendaylight.yangtools.yang.model.api.ChoiceSchemaNode;
44 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
45 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
46 import org.opendaylight.yangtools.yang.model.api.DerivableSchemaNode;
47 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
48 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
49 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
50 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
55 * Runtime Context for Java YANG Binding classes. It provides information derived from the backing effective model,
56 * which is not captured in generated classes (and hence cannot be obtained from {@code BindingReflections}.
58 * <p>Some of this information are for example list of all available children for cases
59 * {@link #getChoiceCaseChildren(DataNodeContainer)}, since choices are augmentable and new choices may be introduced
60 * by additional models. Same goes for all possible augmentations.
63 public abstract class AbstractBindingRuntimeContext implements BindingRuntimeContext {
64 private static final Logger LOG = LoggerFactory.getLogger(AbstractBindingRuntimeContext.class);
66 private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
67 new CacheLoader<QName, Class<?>>() {
69 public Class<?> load(final QName key) {
70 final Optional<Type> identityType = getTypes().findIdentity(key);
71 checkArgument(identityType.isPresent(), "Supplied QName %s is not a valid identity", key);
73 return loadClass(identityType.get());
74 } catch (final ClassNotFoundException e) {
75 throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
81 public final <T extends Augmentation<?>> AugmentationSchemaNode getAugmentationDefinition(final Class<T> augClass) {
82 return getTypes().findAugmentation(Type.of(augClass)).orElse(null);
86 public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
87 checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
89 checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
90 return (DataSchemaNode) getTypes().findSchema(Type.of(cls)).orElse(null);
94 public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
95 return (ActionDefinition) getTypes().findSchema(Type.of(cls)).orElse(null);
99 public final Absolute getActionIdentifier(final Class<? extends Action<?, ?, ?>> cls) {
100 return getTypes().findSchemaNodeIdentifier(Type.of(cls)).orElse(null);
104 public final Entry<AugmentationIdentifier, AugmentationSchemaNode> getResolvedAugmentationSchema(
105 final DataNodeContainer target, final Class<? extends Augmentation<?>> aug) {
106 final AugmentationSchemaNode origSchema = getAugmentationDefinition(aug);
107 checkArgument(origSchema != null, "Augmentation %s is not known in current schema context", aug);
109 * FIXME: Validate augmentation schema lookup
111 * Currently this algorithm, does not verify if instantiated child nodes
112 * are real one derived from augmentation schema. The problem with
113 * full validation is, if user used copy builders, he may use
114 * augmentation which was generated for different place.
116 * If this augmentations have same definition, we emit same identifier
117 * with data and it is up to underlying user to validate data.
120 final Set<QName> childNames = new HashSet<>();
121 final Set<DataSchemaNode> realChilds = new HashSet<>();
122 for (final DataSchemaNode child : origSchema.getChildNodes()) {
123 final DataSchemaNode dataChildQNname = target.dataChildByName(child.getQName());
124 final String childLocalName = child.getQName().getLocalName();
125 if (dataChildQNname == null) {
126 for (DataSchemaNode dataSchemaNode : target.getChildNodes()) {
127 if (childLocalName.equals(dataSchemaNode.getQName().getLocalName())) {
128 realChilds.add(dataSchemaNode);
129 childNames.add(dataSchemaNode.getQName());
133 realChilds.add(dataChildQNname);
134 childNames.add(child.getQName());
138 final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
139 final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
140 return new SimpleEntry<>(identifier, proxy);
144 public final Optional<CaseSchemaNode> getCaseSchemaDefinition(final ChoiceSchemaNode schema,
145 final Class<?> childClass) {
146 final DataSchemaNode origSchema = getSchemaDefinition(childClass);
147 checkArgument(origSchema instanceof CaseSchemaNode, "Supplied schema %s is not case.", origSchema);
149 /* FIXME: Make sure that if there are multiple augmentations of same
150 * named case, with same structure we treat it as equals
151 * this is due property of Binding specification and copy builders
152 * that user may be unaware that he is using incorrect case
153 * which was generated for choice inside grouping.
155 return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
159 public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
160 return getTypeWithSchema(getTypes(), Type.of(type));
163 private static @NonNull Entry<GeneratedType, WithStatus> getTypeWithSchema(final BindingRuntimeTypes types,
164 final Type referencedType) {
165 final WithStatus schema = types.findSchema(referencedType).orElseThrow(
166 () -> new NullPointerException("Failed to find schema for type " + referencedType));
167 final Type definedType = types.findType(schema).orElseThrow(
168 () -> new NullPointerException("Failed to find defined type for " + referencedType + " schema " + schema));
170 if (definedType instanceof GeneratedTypeBuilder) {
171 return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
173 checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
174 return new SimpleEntry<>((GeneratedType) definedType, schema);
178 public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
179 return getChoiceCaseChildren(getTypes(), schema);
182 private static @NonNull ImmutableMap<Type, Entry<Type, Type>> getChoiceCaseChildren(final BindingRuntimeTypes types,
183 final DataNodeContainer schema) {
184 final Map<Type, Entry<Type, Type>> childToCase = new HashMap<>();
186 for (final ChoiceSchemaNode choice : Iterables.filter(schema.getChildNodes(), ChoiceSchemaNode.class)) {
187 final ChoiceSchemaNode originalChoice = getOriginalSchema(choice);
188 final Optional<Type> optType = types.findType(originalChoice);
189 checkState(optType.isPresent(), "Failed to find generated type for choice %s", originalChoice);
190 final Type choiceType = optType.get();
192 for (Type caze : types.findCases(choiceType)) {
193 final Entry<Type,Type> caseIdentifier = new SimpleEntry<>(choiceType, caze);
194 final HashSet<Type> caseChildren = new HashSet<>();
195 if (caze instanceof GeneratedTypeBuilder) {
196 caze = ((GeneratedTypeBuilder) caze).build();
198 collectAllContainerTypes((GeneratedType) caze, caseChildren);
199 for (final Type caseChild : caseChildren) {
200 childToCase.put(caseChild, caseIdentifier);
204 return ImmutableMap.copyOf(childToCase);
208 public final Set<Class<?>> getCases(final Class<?> choice) {
209 final Collection<Type> cazes = getTypes().findCases(Type.of(choice));
210 final Set<Class<?>> ret = new HashSet<>(cazes.size());
211 for (final Type caze : cazes) {
213 ret.add(loadClass(caze));
214 } catch (final ClassNotFoundException e) {
215 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
222 public final Class<?> getClassForSchema(final SchemaNode childSchema) {
223 final SchemaNode origSchema = getOriginalSchema(childSchema);
224 final Optional<Type> clazzType = getTypes().findType(origSchema);
225 checkArgument(clazzType.isPresent(), "Failed to find binding type for %s (original %s)",
226 childSchema, origSchema);
229 return loadClass(clazzType.get());
230 } catch (final ClassNotFoundException e) {
231 throw new IllegalStateException(e);
236 public final ImmutableMap<AugmentationIdentifier, Type> getAvailableAugmentationTypes(
237 final DataNodeContainer container) {
238 if (container instanceof AugmentationTarget) {
239 final Map<AugmentationIdentifier, Type> identifierToType = new HashMap<>();
240 final BindingRuntimeTypes types = getTypes();
241 for (final AugmentationSchemaNode augment : ((AugmentationTarget) container).getAvailableAugmentations()) {
242 // Augmentation must have child nodes if is to be used with Binding classes
243 AugmentationSchemaNode augOrig = augment;
244 while (augOrig.getOriginalDefinition().isPresent()) {
245 augOrig = augOrig.getOriginalDefinition().get();
248 if (!augment.getChildNodes().isEmpty()) {
249 final Optional<Type> augType = types.findType(augOrig);
250 if (augType.isPresent()) {
251 identifierToType.put(getAugmentationIdentifier(augment), augType.get());
255 return ImmutableMap.copyOf(identifierToType);
258 return ImmutableMap.of();
262 public final Class<?> getIdentityClass(final QName input) {
263 return identityClasses.getUnchecked(input);
266 private static AugmentationIdentifier getAugmentationIdentifier(final AugmentationSchemaNode augment) {
267 // FIXME: use DataSchemaContextNode.augmentationIdentifierFrom() once it does caching
268 return AugmentationIdentifier.create(augment.getChildNodes().stream().map(DataSchemaNode::getQName)
269 .collect(ImmutableSet.toImmutableSet()));
272 private static Set<Type> collectAllContainerTypes(final GeneratedType type, final Set<Type> collection) {
273 for (final MethodSignature definition : type.getMethodDefinitions()) {
274 Type childType = definition.getReturnType();
275 if (childType instanceof ParameterizedType) {
276 childType = ((ParameterizedType) childType).getActualTypeArguments()[0];
278 if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
279 collection.add(childType);
282 for (final Type parent : type.getImplements()) {
283 if (parent instanceof GeneratedType) {
284 collectAllContainerTypes((GeneratedType) parent, collection);
290 private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
291 @SuppressWarnings("unchecked")
292 final T original = (T) originalNodeOf(choice);
293 if (original != null) {
299 private static @NonNull Optional<CaseSchemaNode> findInstantiatedCase(final ChoiceSchemaNode instantiatedChoice,
300 final CaseSchemaNode originalDefinition) {
301 CaseSchemaNode potential = instantiatedChoice.findCase(originalDefinition.getQName()).orElse(null);
302 if (originalDefinition.equals(potential)) {
303 return Optional.of(potential);
305 if (potential != null) {
306 SchemaNode potentialRoot = originalNodeOf(potential);
307 if (originalDefinition.equals(potentialRoot)) {
308 return Optional.of(potential);
312 // We try to find case by name, then lookup its root definition
313 // and compare it with original definition
314 // This solves case, if choice was inside grouping
315 // which was used in different module and thus namespaces are
316 // different, but local names are still same.
318 // Still we need to check equality of definition, because local name is not
319 // sufficient to uniquelly determine equality of cases
321 for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
322 if (originalDefinition.equals(originalNodeOf(caze))) {
323 return Optional.of(caze);
326 return Optional.empty();
329 private static @Nullable SchemaNode originalNodeOf(final SchemaNode node) {
330 return node instanceof DerivableSchemaNode ? ((DerivableSchemaNode) node).getOriginal().orElse(null) : null;