Lower DataObjectCodecContext method visibility
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / DataObjectCodecContext.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.dom.codec.impl;
9
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;
25 import java.util.Map;
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.mdsal.binding.generator.api.ClassLoadingStrategy;
34 import org.opendaylight.mdsal.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.AugmentationSchemaNode;
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;
56
57 abstract class DataObjectCodecContext<D extends DataObject, T extends DataNodeContainer>
58         extends DataContainerCodecContext<D, T> {
59     private static final Logger LOG = LoggerFactory.getLogger(DataObjectCodecContext.class);
60     private static final MethodType CONSTRUCTOR_TYPE = MethodType.methodType(void.class, InvocationHandler.class);
61     private static final MethodType DATAOBJECT_TYPE = MethodType.methodType(DataObject.class, InvocationHandler.class);
62     private static final Comparator<Method> METHOD_BY_ALPHABET = (o1, o2) -> o1.getName().compareTo(o2.getName());
63
64     private final ImmutableMap<String, LeafNodeCodecContext<?>> leafChild;
65     private final ImmutableMap<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYang;
66     private final ImmutableSortedMap<Method, NodeContextSupplier> byMethod;
67     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byStreamClass;
68     private final ImmutableMap<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClass;
69     private final ImmutableMap<AugmentationIdentifier, Type> possibleAugmentations;
70     private final MethodHandle proxyConstructor;
71
72     private final ConcurrentMap<YangInstanceIdentifier.PathArgument, DataContainerCodecPrototype<?>> byYangAugmented =
73             new ConcurrentHashMap<>();
74     private final ConcurrentMap<Class<?>, DataContainerCodecPrototype<?>> byStreamAugmented = new ConcurrentHashMap<>();
75
76     DataObjectCodecContext(final DataContainerCodecPrototype<T> prototype) {
77         super(prototype);
78
79         this.leafChild = factory().getLeafNodes(getBindingClass(), getSchema());
80
81         final Map<Class<?>, Method> clsToMethod = BindingReflections.getChildrenClassToMethod(getBindingClass());
82
83         final Map<YangInstanceIdentifier.PathArgument, NodeContextSupplier> byYangBuilder = new HashMap<>();
84         final SortedMap<Method, NodeContextSupplier> byMethodBuilder = new TreeMap<>(METHOD_BY_ALPHABET);
85         final Map<Class<?>, DataContainerCodecPrototype<?>> byStreamClassBuilder = new HashMap<>();
86         final Map<Class<?>, DataContainerCodecPrototype<?>> byBindingArgClassBuilder = new HashMap<>();
87
88         // Adds leaves to mapping
89         for (final LeafNodeCodecContext<?> leaf : leafChild.values()) {
90             byMethodBuilder.put(leaf.getGetter(), leaf);
91             byYangBuilder.put(leaf.getDomPathArgument(), leaf);
92         }
93
94         for (final Entry<Class<?>, Method> childDataObj : clsToMethod.entrySet()) {
95             final DataContainerCodecPrototype<?> childProto = loadChildPrototype(childDataObj.getKey());
96             byMethodBuilder.put(childDataObj.getValue(), childProto);
97             byStreamClassBuilder.put(childProto.getBindingClass(), childProto);
98             byYangBuilder.put(childProto.getYangArg(), childProto);
99             if (childProto.isChoice()) {
100                 final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) childProto.get();
101                 for (final Class<?> cazeChild : choice.getCaseChildrenClasses()) {
102                     byBindingArgClassBuilder.put(cazeChild, childProto);
103                 }
104             }
105         }
106         this.byMethod = ImmutableSortedMap.copyOfSorted(byMethodBuilder);
107         this.byYang = ImmutableMap.copyOf(byYangBuilder);
108         this.byStreamClass = ImmutableMap.copyOf(byStreamClassBuilder);
109         byBindingArgClassBuilder.putAll(byStreamClass);
110         this.byBindingArgClass = ImmutableMap.copyOf(byBindingArgClassBuilder);
111
112
113         if (Augmentable.class.isAssignableFrom(getBindingClass())) {
114             this.possibleAugmentations = factory().getRuntimeContext().getAvailableAugmentationTypes(getSchema());
115         } else {
116             this.possibleAugmentations = ImmutableMap.of();
117         }
118         reloadAllAugmentations();
119
120         final Class<?> proxyClass = Proxy.getProxyClass(getBindingClass().getClassLoader(), getBindingClass(),
121             AugmentationHolder.class);
122         try {
123             proxyConstructor = MethodHandles.publicLookup().findConstructor(proxyClass, CONSTRUCTOR_TYPE)
124                     .asType(DATAOBJECT_TYPE);
125         } catch (NoSuchMethodException | IllegalAccessException e) {
126             throw new IllegalStateException("Failed to find contructor for class " + proxyClass, e);
127         }
128     }
129
130     private void reloadAllAugmentations() {
131         for (final Entry<AugmentationIdentifier, Type> augment : possibleAugmentations.entrySet()) {
132             final DataContainerCodecPrototype<?> augProto = getAugmentationPrototype(augment.getValue());
133             if (augProto != null) {
134                 byYangAugmented.putIfAbsent(augProto.getYangArg(), augProto);
135                 byStreamAugmented.putIfAbsent(augProto.getBindingClass(), augProto);
136             }
137         }
138     }
139
140     @SuppressWarnings("unchecked")
141     @Override
142     public <C extends DataObject> DataContainerCodecContext<C, ?> streamChild(final Class<C> childClass) {
143         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
144         return (DataContainerCodecContext<C, ?>) childNonNull(childProto, childClass, " Child %s is not valid child.",
145                 childClass).get();
146     }
147
148     private DataContainerCodecPrototype<?> streamChildPrototype(final Class<?> childClass) {
149         final DataContainerCodecPrototype<?> childProto = byStreamClass.get(childClass);
150         if (childProto != null) {
151             return childProto;
152         }
153         if (Augmentation.class.isAssignableFrom(childClass)) {
154             return augmentationByClass(childClass);
155         }
156         return null;
157     }
158
159     @SuppressWarnings("unchecked")
160     @Override
161     public <C extends DataObject> Optional<DataContainerCodecContext<C, ?>> possibleStreamChild(
162             final Class<C> childClass) {
163         final DataContainerCodecPrototype<?> childProto = streamChildPrototype(childClass);
164         if (childProto != null) {
165             return Optional.of((DataContainerCodecContext<C, ?>) childProto.get());
166         }
167         return Optional.absent();
168     }
169
170     @Override
171     public DataContainerCodecContext<?,?> bindingPathArgumentChild(final InstanceIdentifier.PathArgument arg,
172             final List<YangInstanceIdentifier.PathArgument> builder) {
173
174         final Class<? extends DataObject> argType = arg.getType();
175         DataContainerCodecPrototype<?> ctxProto = byBindingArgClass.get(argType);
176         if (ctxProto == null && Augmentation.class.isAssignableFrom(argType)) {
177             ctxProto = augmentationByClass(argType);
178         }
179         final DataContainerCodecContext<?, ?> context =
180                 childNonNull(ctxProto, argType, "Class %s is not valid child of %s", argType, getBindingClass()).get();
181         if (context instanceof ChoiceNodeCodecContext) {
182             final ChoiceNodeCodecContext<?> choice = (ChoiceNodeCodecContext<?>) context;
183             final DataContainerCodecContext<?, ?> caze = choice.getCazeByChildClass(arg.getType());
184             choice.addYangPathArgument(arg, builder);
185             caze.addYangPathArgument(arg, builder);
186             return caze.bindingPathArgumentChild(arg, builder);
187         }
188         context.addYangPathArgument(arg, builder);
189         return context;
190     }
191
192     @SuppressWarnings("unchecked")
193     @Override
194     public NodeCodecContext<D> yangPathArgumentChild(final YangInstanceIdentifier.PathArgument arg) {
195         final NodeContextSupplier childSupplier;
196         if (arg instanceof NodeIdentifierWithPredicates) {
197             childSupplier = byYang.get(new NodeIdentifier(arg.getNodeType()));
198         } else if (arg instanceof AugmentationIdentifier) {
199             childSupplier = yangAugmentationChild((AugmentationIdentifier) arg);
200         } else {
201             childSupplier = byYang.get(arg);
202         }
203
204         return (NodeCodecContext<D>) childNonNull(childSupplier, arg,
205             "Argument %s is not valid child of %s", arg, getSchema()).get();
206     }
207
208     protected final LeafNodeCodecContext<?> getLeafChild(final String name) {
209         final LeafNodeCodecContext<?> value = leafChild.get(name);
210         return IncorrectNestingException.checkNonNull(value, "Leaf %s is not valid for %s", name, getBindingClass());
211     }
212
213     private DataContainerCodecPrototype<?> loadChildPrototype(final Class<?> childClass) {
214         final DataSchemaNode origDef = factory().getRuntimeContext().getSchemaDefinition(childClass);
215         // Direct instantiation or use in same module in which grouping
216         // was defined.
217         DataSchemaNode sameName;
218         try {
219             sameName = getSchema().getDataChildByName(origDef.getQName());
220         } catch (final IllegalArgumentException e) {
221             sameName = null;
222         }
223         final DataSchemaNode childSchema;
224         if (sameName != null) {
225             // Exactly same schema node
226             if (origDef.equals(sameName)) {
227                 childSchema = sameName;
228                 // We check if instantiated node was added via uses
229                 // statement and is instantiation of same grouping
230             } else if (origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(sameName))) {
231                 childSchema = sameName;
232             } else {
233                 // Node has same name, but clearly is different
234                 childSchema = null;
235             }
236         } else {
237             // We are looking for instantiation via uses in other module
238             final QName instantiedName = QName.create(namespace(), origDef.getQName().getLocalName());
239             final DataSchemaNode potential = getSchema().getDataChildByName(instantiedName);
240             // We check if it is really instantiated from same
241             // definition as class was derived
242             if (potential != null && origDef.equals(SchemaNodeUtils.getRootOriginalIfPossible(potential))) {
243                 childSchema = potential;
244             } else {
245                 childSchema = null;
246             }
247         }
248         final DataSchemaNode nonNullChild =
249                 childNonNull(childSchema, childClass, "Node %s does not have child named %s", getSchema(), childClass);
250         return DataContainerCodecPrototype.from(childClass, nonNullChild, factory());
251     }
252
253     private DataContainerCodecPrototype<?> yangAugmentationChild(final AugmentationIdentifier arg) {
254         final DataContainerCodecPrototype<?> firstTry = byYangAugmented.get(arg);
255         if (firstTry != null) {
256             return firstTry;
257         }
258         if (possibleAugmentations.containsKey(arg)) {
259             reloadAllAugmentations();
260             return byYangAugmented.get(arg);
261         }
262         return null;
263     }
264
265     @Nullable
266     private DataContainerCodecPrototype<?> augmentationByClass(@Nonnull final Class<?> childClass) {
267         final DataContainerCodecPrototype<?> firstTry = augmentationByClassOrEquivalentClass(childClass);
268         if (firstTry != null) {
269             return firstTry;
270         }
271         reloadAllAugmentations();
272         return augmentationByClassOrEquivalentClass(childClass);
273     }
274
275     @Nullable
276     private DataContainerCodecPrototype<?> augmentationByClassOrEquivalentClass(@Nonnull final Class<?> childClass) {
277         final DataContainerCodecPrototype<?> childProto = byStreamAugmented.get(childClass);
278         if (childProto != null) {
279             return childProto;
280         }
281
282         /*
283          * It is potentially mismatched valid augmentation - we look up equivalent augmentation
284          * using reflection and walk all stream child and compare augmenations classes if they are
285          * equivalent.
286          *
287          * FIXME: Cache mapping of mismatched augmentation to real one, to speed up lookup.
288          */
289         @SuppressWarnings("rawtypes")
290         final Class<?> augTarget = BindingReflections.findAugmentationTarget((Class) childClass);
291         if (getBindingClass().equals(augTarget)) {
292             for (final DataContainerCodecPrototype<?> realChild : byStreamAugmented.values()) {
293                 if (Augmentation.class.isAssignableFrom(realChild.getBindingClass())
294                         && BindingReflections.isSubstitutionFor(childClass, realChild.getBindingClass())) {
295                     return realChild;
296                 }
297             }
298         }
299         return null;
300     }
301
302     private DataContainerCodecPrototype<?> getAugmentationPrototype(final Type value) {
303         final ClassLoadingStrategy loader = factory().getRuntimeContext().getStrategy();
304         @SuppressWarnings("rawtypes")
305         final Class augClass;
306         try {
307             augClass = loader.loadClass(value);
308         } catch (final ClassNotFoundException e) {
309             LOG.debug("Failed to load augmentation prototype for {}. Will be retried when needed.", value, e);
310             return null;
311         }
312
313         @SuppressWarnings("unchecked")
314         final Entry<AugmentationIdentifier, AugmentationSchemaNode> augSchema = factory().getRuntimeContext()
315                 .getResolvedAugmentationSchema(getSchema(), augClass);
316         return DataContainerCodecPrototype.from(augClass, augSchema.getKey(), augSchema.getValue(), factory());
317     }
318
319     @SuppressWarnings("rawtypes")
320     Object getBindingChildValue(final Method method, final NormalizedNodeContainer domData) {
321         final NodeCodecContext<?> childContext = byMethod.get(method).get();
322         @SuppressWarnings("unchecked")
323         final java.util.Optional<NormalizedNode<?, ?>> domChild = domData.getChild(childContext.getDomPathArgument());
324         if (domChild.isPresent()) {
325             return childContext.deserializeObject(domChild.get());
326         } else if (childContext instanceof LeafNodeCodecContext) {
327             return ((LeafNodeCodecContext)childContext).defaultObject();
328         } else {
329             return null;
330         }
331     }
332
333     @SuppressWarnings("checkstyle:illegalCatch")
334     protected final D createBindingProxy(final NormalizedNodeContainer<?, ?, ?> node) {
335         try {
336             return (D) proxyConstructor.invokeExact((InvocationHandler)new LazyDataObject<>(this, node));
337         } catch (final Throwable e) {
338             Throwables.throwIfUnchecked(e);
339             throw new RuntimeException(e);
340         }
341     }
342
343     @SuppressWarnings("unchecked")
344     Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentationsFrom(
345             final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data) {
346
347         @SuppressWarnings("rawtypes")
348         final Map map = new HashMap<>();
349
350         for (final NormalizedNode<?, ?> childValue : data.getValue()) {
351             if (childValue instanceof AugmentationNode) {
352                 final AugmentationNode augDomNode = (AugmentationNode) childValue;
353                 final DataContainerCodecPrototype<?> codecProto = yangAugmentationChild(augDomNode.getIdentifier());
354                 if (codecProto != null) {
355                     final DataContainerCodecContext<?, ?> codec = codecProto.get();
356                     map.put(codec.getBindingClass(), codec.deserializeObject(augDomNode));
357                 }
358             }
359         }
360         for (final DataContainerCodecPrototype<?> value : byStreamAugmented.values()) {
361             final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(value.getYangArg());
362             if (augData.isPresent()) {
363                 map.put(value.getBindingClass(), value.get().deserializeObject(augData.get()));
364             }
365         }
366         return map;
367     }
368
369     Collection<Method> getHashCodeAndEqualsMethods() {
370         return byMethod.keySet();
371     }
372
373     @Override
374     public InstanceIdentifier.PathArgument deserializePathArgument(final YangInstanceIdentifier.PathArgument arg) {
375         Preconditions.checkArgument(getDomPathArgument().equals(arg));
376         return bindingArg();
377     }
378
379     @Override
380     public YangInstanceIdentifier.PathArgument serializePathArgument(final InstanceIdentifier.PathArgument arg) {
381         Preconditions.checkArgument(bindingArg().equals(arg));
382         return getDomPathArgument();
383     }
384 }