603624cd8f69e3358b66dec2c662bcacf6569bcf
[mdsal.git] / binding / mdsal-binding-runtime-api / src / main / java / org / opendaylight / mdsal / binding / runtime / api / AbstractBindingRuntimeContext.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. and others.  All rights reserved.
3  *
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
7  */
8 package org.opendaylight.mdsal.binding.runtime.api;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12
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;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Optional;
27 import java.util.Set;
28 import org.eclipse.jdt.annotation.NonNull;
29 import org.opendaylight.mdsal.binding.model.api.DefaultType;
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.DocumentedNode.WithStatus;
47 import org.opendaylight.yangtools.yang.model.api.SchemaNode;
48 import org.opendaylight.yangtools.yang.model.api.stmt.SchemaNodeIdentifier.Absolute;
49 import org.opendaylight.yangtools.yang.model.util.EffectiveAugmentationSchema;
50 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
51 import org.slf4j.Logger;
52 import org.slf4j.LoggerFactory;
53
54 /**
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}.
57  *
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.
61  */
62 @Beta
63 public abstract class AbstractBindingRuntimeContext implements BindingRuntimeContext {
64     private static final Logger LOG = LoggerFactory.getLogger(AbstractBindingRuntimeContext.class);
65
66     private final LoadingCache<QName, Class<?>> identityClasses = CacheBuilder.newBuilder().weakValues().build(
67         new CacheLoader<QName, Class<?>>() {
68             @Override
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);
72                 try {
73                     return loadClass(identityType.get());
74                 } catch (final ClassNotFoundException e) {
75                     throw new IllegalArgumentException("Required class " + identityType + "was not found.", e);
76                 }
77             }
78         });
79
80     @Override
81     public final <T extends Augmentation<?>> AugmentationSchemaNode getAugmentationDefinition(final Class<T> augClass) {
82         return getTypes().findAugmentation(DefaultType.of(augClass)).orElse(null);
83     }
84
85     @Override
86     public final DataSchemaNode getSchemaDefinition(final Class<?> cls) {
87         checkArgument(!Augmentation.class.isAssignableFrom(cls), "Supplied class must not be an augmentation (%s is)",
88             cls);
89         checkArgument(!Action.class.isAssignableFrom(cls), "Supplied class must not be an action (%s is)", cls);
90         return (DataSchemaNode) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
91     }
92
93     @Override
94     public final ActionDefinition getActionDefinition(final Class<? extends Action<?, ?, ?>> cls) {
95         return (ActionDefinition) getTypes().findSchema(DefaultType.of(cls)).orElse(null);
96     }
97
98     @Override
99     public final Absolute getActionIdentifier(final Class<? extends Action<?, ?, ?>> cls) {
100         return getTypes().findSchemaNodeIdentifier(DefaultType.of(cls)).orElse(null);
101     }
102
103     @Override
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);
108         /*
109          * FIXME: Validate augmentation schema lookup
110          *
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.
115          *
116          * If this augmentations have same definition, we emit same identifier
117          * with data and it is up to underlying user to validate data.
118          *
119          */
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.getDataChildByName(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());
130                     }
131                 }
132             } else {
133                 realChilds.add(dataChildQNname);
134                 childNames.add(child.getQName());
135             }
136         }
137
138         final AugmentationIdentifier identifier = AugmentationIdentifier.create(childNames);
139         final AugmentationSchemaNode proxy = new EffectiveAugmentationSchema(origSchema, realChilds);
140         return new SimpleEntry<>(identifier, proxy);
141     }
142
143     @Override
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);
148
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.
154          */
155         return findInstantiatedCase(schema, (CaseSchemaNode) origSchema);
156     }
157
158     @Override
159     public final Entry<GeneratedType, WithStatus> getTypeWithSchema(final Class<?> type) {
160         return getTypeWithSchema(getTypes(), DefaultType.of(type));
161     }
162
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));
169
170         if (definedType instanceof GeneratedTypeBuilder) {
171             return new SimpleEntry<>(((GeneratedTypeBuilder) definedType).build(), schema);
172         }
173         checkArgument(definedType instanceof GeneratedType, "Type %s is not a GeneratedType", referencedType);
174         return new SimpleEntry<>((GeneratedType) definedType, schema);
175     }
176
177     @Override
178     public final Map<Type, Entry<Type, Type>> getChoiceCaseChildren(final DataNodeContainer schema) {
179         return getChoiceCaseChildren(getTypes(), schema);
180     }
181
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<>();
185
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();
191
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();
197                 }
198                 collectAllContainerTypes((GeneratedType) caze, caseChildren);
199                 for (final Type caseChild : caseChildren) {
200                     childToCase.put(caseChild, caseIdentifier);
201                 }
202             }
203         }
204         return ImmutableMap.copyOf(childToCase);
205     }
206
207     @Override
208     public final Set<Class<?>> getCases(final Class<?> choice) {
209         final Collection<Type> cazes = getTypes().findCases(DefaultType.of(choice));
210         final Set<Class<?>> ret = new HashSet<>(cazes.size());
211         for (final Type caze : cazes) {
212             try {
213                 ret.add(loadClass(caze));
214             } catch (final ClassNotFoundException e) {
215                 LOG.warn("Failed to load class for case {}, ignoring it", caze, e);
216             }
217         }
218         return ret;
219     }
220
221     @Override
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);
227
228         try {
229             return loadClass(clazzType.get());
230         } catch (final ClassNotFoundException e) {
231             throw new IllegalStateException(e);
232         }
233     }
234
235     @Override
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();
246                 }
247
248                 if (!augment.getChildNodes().isEmpty()) {
249                     final Optional<Type> augType = types.findType(augOrig);
250                     if (augType.isPresent()) {
251                         identifierToType.put(getAugmentationIdentifier(augment), augType.get());
252                     }
253                 }
254             }
255             return ImmutableMap.copyOf(identifierToType);
256         }
257
258         return ImmutableMap.of();
259     }
260
261     @Override
262     public final Class<?> getIdentityClass(final QName input) {
263         return identityClasses.getUnchecked(input);
264     }
265
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()));
270     }
271
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];
277             }
278             if (childType instanceof GeneratedType || childType instanceof GeneratedTypeBuilder) {
279                 collection.add(childType);
280             }
281         }
282         for (final Type parent : type.getImplements()) {
283             if (parent instanceof GeneratedType) {
284                 collectAllContainerTypes((GeneratedType) parent, collection);
285             }
286         }
287         return collection;
288     }
289
290     private static <T extends SchemaNode> T getOriginalSchema(final T choice) {
291         @SuppressWarnings("unchecked")
292         final T original = (T) SchemaNodeUtils.getRootOriginalIfPossible(choice);
293         if (original != null) {
294             return original;
295         }
296         return choice;
297     }
298
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);
304         }
305         if (potential != null) {
306             SchemaNode potentialRoot = SchemaNodeUtils.getRootOriginalIfPossible(potential);
307             if (originalDefinition.equals(potentialRoot)) {
308                 return Optional.of(potential);
309             }
310         }
311
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.
317         //
318         // Still we need to check equality of definition, because local name is not
319         // sufficient to uniquelly determine equality of cases
320         //
321         for (CaseSchemaNode caze : instantiatedChoice.findCaseNodes(originalDefinition.getQName().getLocalName())) {
322             if (originalDefinition.equals(SchemaNodeUtils.getRootOriginalIfPossible(caze))) {
323                 return Optional.of(caze);
324             }
325         }
326         return Optional.empty();
327     }
328 }