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