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.dom.codec.impl;
10 import static com.google.common.base.Preconditions.checkArgument;
12 import com.google.common.base.Throwables;
13 import com.google.common.collect.ImmutableMap;
14 import com.google.common.collect.ImmutableSortedMap;
15 import java.lang.invoke.MethodHandle;
16 import java.lang.invoke.MethodHandles;
17 import java.lang.invoke.MethodType;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.Method;
20 import java.lang.reflect.Proxy;
21 import java.util.Collection;
22 import java.util.Comparator;
23 import java.util.HashMap;
24 import java.util.List;
26 import java.util.Map.Entry;
27 import java.util.Optional;
28 import java.util.SortedMap;
29 import java.util.TreeMap;
30 import java.util.concurrent.ConcurrentHashMap;
31 import java.util.concurrent.ConcurrentMap;
32 import org.eclipse.jdt.annotation.NonNull;
33 import org.eclipse.jdt.annotation.Nullable;
34 import org.opendaylight.mdsal.binding.generator.api.ClassLoadingStrategy;
35 import org.opendaylight.mdsal.binding.model.api.Type;
36 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
37 import org.opendaylight.yangtools.yang.binding.Augmentable;
38 import org.opendaylight.yangtools.yang.binding.Augmentation;
39 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
40 import org.opendaylight.yangtools.yang.binding.DataObject;
41 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
42 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
43 import org.opendaylight.yangtools.yang.common.QName;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
47 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
48 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
49 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
50 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
51 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.AugmentationSchemaNode;
53 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
54 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
55 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
56 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
57 import org.slf4j.Logger;
58 import org.slf4j.LoggerFactory;
60 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer & WithStatus>
61 extends DataContainerCodecContext<D, T> {
62 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
63 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
64 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
65 private static final Comparator<Method> METHOD_BY_ALPHABET = Comparator.comparing(Method::getName);
67 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
68 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
69 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
70 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
71 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
72 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
73 private final MethodHandle proxyConstructor;
75 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
76 new ConcurrentHashMap<>();
77 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
79 DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
82 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
84 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
86 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
87 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
88 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
89 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
91 // Adds leaves to mapping
92 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
93 byMethodBuilder.put(leaf.getGetter(), leaf);
94 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
97 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
98 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
99 byMethodBuilder.put(childDataObj.getValue(), childProto);
100 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
101 byYangBuilder.put(childProto.getYangArg(), childProto);
102 if (childProto.isChoice()) {
103 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
104 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
105 byBindingArgClassBuilder.put(cazeChild, childProto);
109 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
110 this.byYang = ImmutableMap.copyOf(byYangBuilder);
111 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
112 byBindingArgClassBuilder.putAll(byStreamClass);
113 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
116 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
117 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
119 this.possibleAugmentations = ImmutableMap.of();
121 reloadAllAugmentations();
123 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), getBindingClass(),
124 AugmentationHolder.class);
126 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
127 .asType(DATAOBJECT_TYPE);
128 } catch (NoSuchMethodException | IllegalAccessException e) {
129 throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
133 private void reloadAllAugmentations() {
134 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
135 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
136 if (augProto != null) {
137 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
138 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
143 @SuppressWarnings("unchecked")
145 public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
146 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
147 return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
151 private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
152 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
153 if (childProto != null) {
156 if (Augmentation.class.isAssignableFrom(childClass)) {
157 return augmentationByClass(childClass);
162 @SuppressWarnings("unchecked")
164 public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
165 final Class<C> childClass) {
166 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
167 if (childProto != null) {
168 return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
170 return Optional.empty();
174 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
175 final List<YangInstanceIdentifier.PathArgument> builder) {
177 final Class<? extends DataObject> argType = arg.getType();
178 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
179 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
180 ctxProto = augmentationByClass(argType);
182 final DataContainerCodecContext<?, ?> context =
183 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
184 if (context instanceof ChoiceNodeCodecContext) {
185 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
186 choice.addYangPathArgument(arg, builder);
188 final java.util.Optional<? extends Class<? extends DataObject>> caseType = arg.getCaseType();
189 final Class<? extends DataObject> type = arg.getType();
190 final DataContainerCodecContext<?, ?> caze;
191 if (caseType.isPresent()) {
192 // Non-ambiguous addressing this should not pose any problems
193 caze = choice.streamChild(caseType.get());
195 caze = choice.getCaseByChildClass(type);
198 caze.addYangPathArgument(arg, builder);
199 return caze.bindingPathArgumentChild(arg, builder);
201 context.addYangPathArgument(arg, builder);
205 @SuppressWarnings("unchecked")
207 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
208 final NodeContextSupplier childSupplier;
209 if (arg instanceof NodeIdentifierWithPredicates) {
210 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
211 } else if (arg instanceof AugmentationIdentifier) {
212 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
214 childSupplier = byYang.get(arg);
217 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
218 "Argument %s is not valid child of %s", arg, getSchema()).get();
221 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
222 final LeafNodeCodecContext<?> value = leafChild.get(name);
223 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
226 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
227 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
228 // Direct instantiation or use in same module in which grouping
230 DataSchemaNode sameName;
232 sameName = getSchema().getDataChildByName(origDef.getQName());
233 } catch (final IllegalArgumentException e) {
236 final DataSchemaNode childSchema;
237 if (sameName != null) {
238 // Exactly same schema node
239 if (origDef.equals(sameName)) {
240 childSchema = sameName;
241 // We check if instantiated node was added via uses
242 // statement and is instantiation of same grouping
243 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
244 childSchema = sameName;
246 // Node has same name, but clearly is different
250 // We are looking for instantiation via uses in other module
251 final QName instantiedName = origDef.getQName().withModule(namespace());
252 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
253 // We check if it is really instantiated from same
254 // definition as class was derived
255 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
256 childSchema = potential;
261 final DataSchemaNode nonNullChild =
262 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
263 return DataContainerCodecPrototype.from(createBindingArg(childClass, nonNullChild), nonNullChild, factory());
266 @SuppressWarnings("unchecked")
267 Item<?> createBindingArg(final Class<?> childClass, final DataSchemaNode childSchema) {
268 return Item.of((Class<? extends DataObject>) childClass);
271 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
272 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
273 if (firstTry != null) {
276 if (possibleAugmentations.containsKey(arg)) {
277 reloadAllAugmentations();
278 return byYangAugmented.get(arg);
283 private @Nullable DataContainerCodecPrototype<?> augmentationByClass(final @NonNull Class<?> childClass) {
284 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
285 if (firstTry != null) {
288 reloadAllAugmentations();
289 return augmentationByClassOrEquivalentClass(childClass);
292 private @Nullable DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(
293 final @NonNull Class<?> childClass) {
294 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
295 if (childProto != null) {
300 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
301 * using reflection and walk all stream child and compare augmenations classes if they are
304 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
306 @SuppressWarnings("rawtypes")
307 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
308 if (getBindingClass().equals(augTarget)) {
309 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
310 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
311 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
319 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
320 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
321 @SuppressWarnings("rawtypes")
322 final Class augClass;
324 augClass = loader.loadClass(value);
325 } catch (final ClassNotFoundException e) {
326 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
330 @SuppressWarnings("unchecked")
331 final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
332 .getResolvedAugmentationSchema(getSchema(), augClass);
333 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
336 @SuppressWarnings("rawtypes")
337 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
338 final NodeCodecContext<?> childContext = byMethod.get(method).get();
339 @SuppressWarnings("unchecked")
340 final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
341 if (domChild.isPresent()) {
342 return childContext.deserializeObject(domChild.get());
343 } else if (childContext instanceof LeafNodeCodecContext) {
344 return ((LeafNodeCodecContext)childContext).defaultObject();
350 @SuppressWarnings("checkstyle:illegalCatch")
351 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
353 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
354 } catch (final Throwable e) {
355 Throwables.throwIfUnchecked(e);
356 throw new RuntimeException(e);
360 @SuppressWarnings("unchecked")
361 Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
362 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
364 @SuppressWarnings("rawtypes")
365 final Map map = new HashMap<>();
367 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
368 if (childValue instanceof AugmentationNode) {
369 final AugmentationNode augDomNode = (AugmentationNode) childValue;
370 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
371 if (codecProto != null) {
372 final DataContainerCodecContext<?, ?> codec = codecProto.get();
373 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
377 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
378 final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
379 if (augData.isPresent()) {
380 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
386 Collection<Method> getHashCodeAndEqualsMethods() {
387 return byMethod.keySet();
391 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
392 checkArgument(getDomPathArgument().equals(arg));
397 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
398 checkArgument(bindingArg().equals(arg));
399 return getDomPathArgument();