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.yangtools.binding.data.codec.impl;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
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.SortedMap;
28 import java.util.TreeMap;
29 import java.util.concurrent.ConcurrentHashMap;
30 import java.util.concurrent.ConcurrentMap;
31 import javax.annotation.Nonnull;
32 import javax.annotation.Nullable;
33 import org.opendaylight.yangtools.sal.binding.generator.api.ClassLoadingStrategy;
34 import org.opendaylight.yangtools.sal.binding.model.api.Type;
35 import org.opendaylight.yangtools.yang.binding.Augmentable;
36 import org.opendaylight.yangtools.yang.binding.Augmentation;
37 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
38 import org.opendaylight.yangtools.yang.binding.DataObject;
39 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
40 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
41 import org.opendaylight.yangtools.yang.common.QName;
42 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
43 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.AugmentationIdentifier;
44 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifier;
45 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.NodeIdentifierWithPredicates;
46 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
47 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
48 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
49 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
50 import org.opendaylight.yangtools.yang.model.api.AugmentationSchema;
51 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
52 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
53 import org.opendaylight.yangtools.yang.model.util.SchemaNodeUtils;
54 import org.slf4j.Logger;
55 import org.slf4j.LoggerFactory;
57 abstract class DataObjectCodecContext<D extends DataObject,T extends DataNodeContainer> extends DataContainerCodecContext<D,T> {
58 private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
59 private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
60 private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
61 private static final Comparator<Method> METHOD_BY_ALPHABET = new Comparator<Method>() {
63 public int compare(final Method o1, final Method o2) {
64 return o1.getName().compareTo(o2.getName());
68 private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
69 private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
70 private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
71 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
72 private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
73 private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
74 private final MethodHandle proxyConstructor;
76 private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
77 new ConcurrentHashMap<>();
78 private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
81 protected DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
84 this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
86 final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
88 final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
89 final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
90 final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
91 final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
93 // Adds leaves to mapping
94 for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
95 byMethodBuilder.put(leaf.getGetter(), leaf);
96 byYangBuilder.put(leaf.getDomPathArgument(), leaf);
99 for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
100 final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
101 byMethodBuilder.put(childDataObj.getValue(), childProto);
102 byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
103 byYangBuilder.put(childProto.getYangArg(), childProto);
104 if (childProto.isChoice()) {
105 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
106 for(final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
107 byBindingArgClassBuilder.put(cazeChild, childProto);
111 this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
112 this.byYang = ImmutableMap.copyOf(byYangBuilder);
113 this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
114 byBindingArgClassBuilder.putAll(byStreamClass);
115 this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
118 if (Augmentable.class.isAssignableFrom(getBindingClass())) {
119 this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
121 this.possibleAugmentations = ImmutableMap.of();
123 reloadAllAugmentations();
125 final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), new Class[] { getBindingClass(), AugmentationHolder.class });
127 proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
128 .asType(DATAOBJECT_TYPE);
129 } catch (NoSuchMethodException | IllegalAccessException e) {
130 throw new IllegalStateException("Failed to find contructor for class " + proxyClass);
134 private void reloadAllAugmentations() {
135 for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
136 final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
137 if (augProto != null) {
138 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
139 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
144 @SuppressWarnings("unchecked")
146 public <DV extends DataObject> DataContainerCodecContext<DV, ?> streamChild(final Class<DV> childClass) {
147 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
148 return (DataContainerCodecContext<DV, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
152 private final DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
153 final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
154 if (childProto != null) {
157 if (Augmentation.class.isAssignableFrom(childClass)) {
158 return augmentationByClass(childClass);
163 @SuppressWarnings("unchecked")
165 public <DV extends DataObject> Optional<DataContainerCodecContext<DV, ?>> possibleStreamChild(
166 final Class<DV> childClass) {
167 final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
168 if (childProto != null) {
169 return Optional.<DataContainerCodecContext<DV,?>>of((DataContainerCodecContext<DV,?>) childProto.get());
171 return Optional.absent();
175 public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
176 final List<YangInstanceIdentifier.PathArgument> builder) {
178 final Class<? extends DataObject> argType = arg.getType();
179 DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
180 if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
181 ctxProto = augmentationByClass(argType);
183 final DataContainerCodecContext<?, ?> context =
184 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
185 if (context instanceof ChoiceNodeCodecContext) {
186 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
187 final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
188 choice.addYangPathArgument(arg, builder);
189 caze.addYangPathArgument(arg, builder);
190 return caze.bindingPathArgumentChild(arg, builder);
192 context.addYangPathArgument(arg, builder);
196 @SuppressWarnings("unchecked")
198 public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
199 final NodeContextSupplier childSupplier;
200 if (arg instanceof NodeIdentifierWithPredicates) {
201 childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
202 } else if (arg instanceof AugmentationIdentifier) {
203 childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
205 childSupplier = byYang.get(arg);
208 return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
209 "Argument %s is not valid child of %s", arg, getSchema()).get();
212 protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
213 final LeafNodeCodecContext<?> value = leafChild.get(name);
214 return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
217 private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
218 final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
219 // Direct instantiation or use in same module in which grouping
221 DataSchemaNode sameName;
223 sameName = getSchema().getDataChildByName(origDef.getQName());
224 } catch (final IllegalArgumentException e) {
227 final DataSchemaNode childSchema;
228 if (sameName != null) {
229 // Exactly same schema node
230 if (origDef.equals(sameName)) {
231 childSchema = sameName;
232 // We check if instantiated node was added via uses
233 // statement and is instantiation of same grouping
234 } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
235 childSchema = sameName;
237 // Node has same name, but clearly is different
241 // We are looking for instantiation via uses in other module
242 final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
243 final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
244 // We check if it is really instantiated from same
245 // definition as class was derived
246 if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
247 childSchema = potential;
252 final DataSchemaNode nonNullChild =
253 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
254 return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
257 private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
258 final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
259 if (firstTry != null) {
262 if (possibleAugmentations.containsKey(arg)) {
263 reloadAllAugmentations();
264 return byYangAugmented.get(arg);
270 private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
271 final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
272 if (firstTry != null) {
275 reloadAllAugmentations();
276 return augmentationByClassOrEquivalentClass(childClass);
280 private final DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
281 final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
282 if (childProto != null) {
287 * It is potentially mismatched valid augmentation - we look up equivalent augmentation
288 * using reflection and walk all stream child and compare augmenations classes if they are
291 * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
293 @SuppressWarnings("rawtypes")
294 final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
295 if ((getBindingClass().equals(augTarget))) {
296 for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
297 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
298 && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
306 private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
307 final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
308 @SuppressWarnings("rawtypes")
309 final Class augClass;
311 augClass = loader.loadClass(value);
312 } catch (final ClassNotFoundException e) {
313 LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
317 @SuppressWarnings("unchecked")
318 final Entry<AugmentationIdentifier, AugmentationSchema> augSchema = factory().getRuntimeContext()
319 .getResolvedAugmentationSchema(getSchema(), augClass);
320 return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
323 @SuppressWarnings("rawtypes")
324 Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
325 final NodeCodecContext<?> childContext = byMethod.get(method).get();
326 @SuppressWarnings("unchecked")
327 final Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
328 if (domChild.isPresent()) {
329 return childContext.deserializeObject(domChild.get());
330 } else if (childContext instanceof LeafNodeCodecContext) {
331 return ((LeafNodeCodecContext)childContext).defaultObject();
337 protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
339 return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
340 } catch (final Throwable e) {
341 throw Throwables.propagate(e);
345 @SuppressWarnings("unchecked")
346 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
347 final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
349 @SuppressWarnings("rawtypes")
350 final Map map = new HashMap<>();
352 for (final NormalizedNode<?, ?> childValue : data.getValue()) {
353 if (childValue instanceof AugmentationNode) {
354 final AugmentationNode augDomNode = (AugmentationNode) childValue;
355 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
356 if (codecProto != null) {
357 final DataContainerCodecContext<?, ?> codec = codecProto.get();
358 map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
362 for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
363 final Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
364 if (augData.isPresent()) {
365 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
371 public Collection<Method> getHashCodeAndEqualsMethods() {
372 return byMethod.keySet();
376 public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
377 Preconditions.checkArgument(getDomPathArgument().equals(arg));
382 public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
383 Preconditions.checkArgument(bindingArg().equals(arg));
384 return getDomPathArgument();