BUG-868: do not use deprecated InstanceIdentifier methods
[controller.git] / opendaylight / md-sal / sal-binding-broker / src / main / java / org / opendaylight / controller / md / sal / binding / impl / BindingToNormalizedNodeCodec.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.controller.md.sal.binding.impl;
9
10 import java.lang.reflect.Method;
11 import java.lang.reflect.Type;
12 import java.util.AbstractMap.SimpleEntry;
13 import java.util.LinkedList;
14 import java.util.List;
15 import java.util.Map.Entry;
16
17 import javax.annotation.Nullable;
18
19 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationException;
20 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizationOperation;
21 import org.opendaylight.controller.md.sal.common.impl.util.compat.DataNormalizer;
22 import org.opendaylight.yangtools.yang.binding.Augmentation;
23 import org.opendaylight.yangtools.yang.binding.DataContainer;
24 import org.opendaylight.yangtools.yang.binding.DataObject;
25 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
26 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.Item;
27 import org.opendaylight.yangtools.yang.binding.util.BindingReflections;
28 import org.opendaylight.yangtools.yang.binding.util.ClassLoaderUtils;
29 import org.opendaylight.yangtools.yang.common.QName;
30 import org.opendaylight.yangtools.yang.data.api.CompositeNode;
31 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.AugmentationIdentifier;
32 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.NodeIdentifier;
33 import org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.AugmentationNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.ContainerNode;
36 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerChild;
37 import org.opendaylight.yangtools.yang.data.api.schema.DataContainerNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
39 import org.opendaylight.yangtools.yang.data.impl.codec.BindingIndependentMappingService;
40 import org.opendaylight.yangtools.yang.data.impl.codec.DeserializationException;
41 import org.opendaylight.yangtools.yang.data.impl.schema.Builders;
42 import org.opendaylight.yangtools.yang.model.api.SchemaContext;
43 import org.opendaylight.yangtools.yang.model.api.SchemaContextListener;
44 import org.slf4j.Logger;
45 import org.slf4j.LoggerFactory;
46
47 import com.google.common.base.Function;
48 import com.google.common.base.Optional;
49 import com.google.common.base.Preconditions;
50 import com.google.common.base.Supplier;
51 import com.google.common.collect.ImmutableList;
52 import com.google.common.collect.Iterables;
53
54 public class BindingToNormalizedNodeCodec implements SchemaContextListener {
55
56     private static final Logger LOG = LoggerFactory.getLogger(BindingToNormalizedNodeCodec.class);
57
58     private final BindingIndependentMappingService bindingToLegacy;
59     private DataNormalizer legacyToNormalized;
60
61     public BindingToNormalizedNodeCodec(final BindingIndependentMappingService mappingService) {
62         super();
63         this.bindingToLegacy = mappingService;
64     }
65
66     public org.opendaylight.yangtools.yang.data.api.InstanceIdentifier toNormalized(
67             final InstanceIdentifier<? extends DataObject> binding) {
68
69         // Used instance-identifier codec do not support serialization of last
70         // path
71         // argument if it is Augmentation (behaviour expected by old datastore)
72         // in this case, we explicitly check if last argument is augmentation
73         // to process it separately
74         if (isAugmentationIdentifier(binding)) {
75             return toNormalizedAugmented(binding);
76         }
77         return toNormalizedImpl(binding);
78     }
79
80     public Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
81             final InstanceIdentifier<? extends DataObject> bindingPath, final DataObject bindingObject) {
82         return toNormalizedNode(toBindingEntry(bindingPath, bindingObject));
83
84     }
85
86     public Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> toNormalizedNode(
87             final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> binding) {
88         Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, CompositeNode> legacyEntry = bindingToLegacy
89                 .toDataDom(binding);
90         Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> normalizedEntry = legacyToNormalized
91                 .toNormalized(legacyEntry);
92         LOG.trace("Serialization of {}, Legacy Representation: {}, Normalized Representation: {}", binding,
93                 legacyEntry, normalizedEntry);
94         if (isAugmentation(binding.getKey().getTargetType())) {
95
96             for (DataContainerChild<? extends PathArgument, ?> child : ((DataContainerNode<?>) normalizedEntry
97                     .getValue()).getValue()) {
98                 if (child instanceof AugmentationNode) {
99                     ImmutableList<PathArgument> childArgs = ImmutableList.<PathArgument> builder()
100                             .addAll(normalizedEntry.getKey().getPathArguments()).add(child.getIdentifier()).build();
101                     org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(
102                             childArgs);
103                     return toDOMEntry(childPath, child);
104                 }
105             }
106
107         }
108         return normalizedEntry;
109
110     }
111
112     /**
113      *
114      * Returns a Binding-Aware instance identifier from normalized
115      * instance-identifier if it is possible to create representation.
116      *
117      * Returns Optional.absent for cases where target is mixin node except
118      * augmentation.
119      *
120      */
121     public Optional<InstanceIdentifier<? extends DataObject>> toBinding(
122             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
123                     throws DeserializationException {
124
125         PathArgument lastArgument = Iterables.getLast(normalized.getPathArguments());
126         // Used instance-identifier codec do not support serialization of last
127         // path
128         // argument if it is AugmentationIdentifier (behaviour expected by old
129         // datastore)
130         // in this case, we explicitly check if last argument is augmentation
131         // to process it separately
132         if (lastArgument instanceof AugmentationIdentifier) {
133             return toBindingAugmented(normalized);
134         }
135         return toBindingImpl(normalized);
136     }
137
138     private Optional<InstanceIdentifier<? extends DataObject>> toBindingAugmented(
139             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
140                     throws DeserializationException {
141         Optional<InstanceIdentifier<? extends DataObject>> potential = toBindingImpl(normalized);
142         // Shorthand check, if codec already supports deserialization
143         // of AugmentationIdentifier we will return
144         if (potential.isPresent() && isAugmentationIdentifier(potential.get())) {
145             return potential;
146         }
147
148         int normalizedCount = getAugmentationCount(normalized);
149         AugmentationIdentifier lastArgument = (AugmentationIdentifier) Iterables.getLast(normalized.getPathArguments());
150
151         // Here we employ small trick - Binding-aware Codec injects an pointer
152         // to augmentation class
153         // if child is referenced - so we will reference child and then shorten
154         // path.
155         LOG.trace("Looking for candidates to match {}", normalized);
156         for (QName child : lastArgument.getPossibleChildNames()) {
157             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier childPath = normalized.node(child);
158             try {
159                 if (isNotRepresentable(childPath)) {
160                     LOG.trace("Path {} is not BI-representable, skipping it", childPath);
161                     continue;
162                 }
163             } catch (DataNormalizationException e) {
164                 LOG.warn("Failed to denormalize path {}, skipping it", childPath, e);
165                 continue;
166             }
167
168             Optional<InstanceIdentifier<? extends DataObject>> baId = toBindingImpl(childPath);
169             if (!baId.isPresent()) {
170                 LOG.debug("No binding-aware identifier found for path {}, skipping it", childPath);
171                 continue;
172             }
173
174             InstanceIdentifier<? extends DataObject> potentialPath = shortenToLastAugment(baId.get());
175             int potentialAugmentCount = getAugmentationCount(potentialPath);
176             if (potentialAugmentCount == normalizedCount) {
177                 LOG.trace("Found matching path {}", potentialPath);
178                 return Optional.<InstanceIdentifier<? extends DataObject>> of(potentialPath);
179             }
180
181             LOG.trace("Skipping mis-matched potential path {}", potentialPath);
182         }
183
184         LOG.trace("Failed to find augmentation matching {}", normalized);
185         return Optional.absent();
186     }
187
188     private Optional<InstanceIdentifier<? extends DataObject>> toBindingImpl(
189             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
190                     throws DeserializationException {
191         org.opendaylight.yangtools.yang.data.api.InstanceIdentifier legacyPath;
192
193         try {
194             if (isNotRepresentable(normalized)) {
195                 return Optional.absent();
196             }
197             legacyPath = legacyToNormalized.toLegacy(normalized);
198         } catch (DataNormalizationException e) {
199             throw new IllegalStateException("Could not denormalize path.", e);
200         }
201         LOG.trace("InstanceIdentifier Path Deserialization: Legacy representation {}, Normalized representation: {}",
202                 legacyPath, normalized);
203         return Optional.<InstanceIdentifier<? extends DataObject>> of(bindingToLegacy.fromDataDom(legacyPath));
204     }
205
206     private boolean isNotRepresentable(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
207             throws DataNormalizationException {
208         DataNormalizationOperation<?> op = findNormalizationOperation(normalized);
209         if( op.isMixin() && op.getIdentifier() instanceof NodeIdentifier) {
210             return true;
211         }
212         if(op.isLeaf()) {
213             return true;
214         }
215         return false;
216     }
217
218     private DataNormalizationOperation<?> findNormalizationOperation(
219             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized)
220                     throws DataNormalizationException {
221         DataNormalizationOperation<?> current = legacyToNormalized.getRootOperation();
222         for (PathArgument arg : normalized.getPathArguments()) {
223             current = current.getChild(arg);
224         }
225         return current;
226     }
227
228     private static final Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject> toBindingEntry(
229             final org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject> key,
230             final DataObject value) {
231         return new SimpleEntry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>(
232                 key, value);
233     }
234
235     private static final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>> toDOMEntry(
236             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier key,
237             final NormalizedNode<?, ?> value) {
238         return new SimpleEntry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, NormalizedNode<?, ?>>(
239                 key, value);
240     }
241
242     public DataObject toBinding(final InstanceIdentifier<?> path, final NormalizedNode<?, ?> normalizedNode)
243             throws DeserializationException {
244         CompositeNode legacy = null;
245         if (isAugmentationIdentifier(path) && normalizedNode instanceof AugmentationNode) {
246             QName augIdentifier = BindingReflections.findQName(path.getTargetType());
247             ContainerNode virtualNode = Builders.containerBuilder() //
248                     .withNodeIdentifier(new NodeIdentifier(augIdentifier)) //
249                     .withChild((DataContainerChild<?, ?>) normalizedNode) //
250                     .build();
251             legacy = (CompositeNode) DataNormalizer.toLegacy(virtualNode);
252         } else {
253             legacy = (CompositeNode) DataNormalizer.toLegacy(normalizedNode);
254         }
255
256         return bindingToLegacy.dataObjectFromDataDom(path, legacy);
257     }
258
259     public DataNormalizer getDataNormalizer() {
260         return legacyToNormalized;
261     }
262
263     public Optional<Entry<org.opendaylight.yangtools.yang.binding.InstanceIdentifier<? extends DataObject>, DataObject>> toBinding(
264             final Entry<org.opendaylight.yangtools.yang.data.api.InstanceIdentifier, ? extends NormalizedNode<?, ?>> normalized)
265                     throws DeserializationException {
266         Optional<InstanceIdentifier<? extends DataObject>> potentialPath = toBinding(normalized.getKey());
267         if (potentialPath.isPresent()) {
268             InstanceIdentifier<? extends DataObject> bindingPath = potentialPath.get();
269             DataObject bindingData = toBinding(bindingPath, normalized.getValue());
270             if (bindingData == null) {
271                 LOG.warn("Failed to deserialize {} to Binding format. Binding path is: {}", normalized, bindingPath);
272             }
273             return Optional.of(toBindingEntry(bindingPath, bindingData));
274         } else {
275             return Optional.absent();
276         }
277     }
278
279     @Override
280     public void onGlobalContextUpdated(final SchemaContext arg0) {
281         legacyToNormalized = new DataNormalizer(arg0);
282     }
283
284     private org.opendaylight.yangtools.yang.data.api.InstanceIdentifier toNormalizedAugmented(
285             final InstanceIdentifier<?> augPath) {
286         org.opendaylight.yangtools.yang.data.api.InstanceIdentifier processed = toNormalizedImpl(augPath);
287         // If used instance identifier codec added supports for deserialization
288         // of last AugmentationIdentifier we will just reuse it
289         if (isAugmentationIdentifier(processed)) {
290             return processed;
291         }
292         // Here we employ small trick - DataNormalizer injects augmentation
293         // identifier if child is
294         // also part of the path (since using a child we can safely identify
295         // augmentation)
296         // so, we scan augmentation for children add it to path
297         // and use original algorithm, then shorten it to last augmentation
298         for (@SuppressWarnings("rawtypes")
299         Class augChild : getAugmentationChildren(augPath.getTargetType())) {
300             @SuppressWarnings("unchecked")
301             InstanceIdentifier<?> childPath = augPath.child(augChild);
302             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = toNormalizedImpl(childPath);
303             org.opendaylight.yangtools.yang.data.api.InstanceIdentifier potentialDiscovered = shortenToLastAugmentation(normalized);
304             if (potentialDiscovered != null) {
305                 return potentialDiscovered;
306             }
307         }
308         return processed;
309     }
310
311     private org.opendaylight.yangtools.yang.data.api.InstanceIdentifier shortenToLastAugmentation(
312             final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized) {
313         int position = 0;
314         int foundPosition = -1;
315         for (PathArgument arg : normalized.getPathArguments()) {
316             position++;
317             if (arg instanceof AugmentationIdentifier) {
318                 foundPosition = position;
319             }
320         }
321         if (foundPosition > 0) {
322             Iterable<PathArgument> shortened = Iterables.limit(normalized.getPathArguments(), foundPosition);
323             return org.opendaylight.yangtools.yang.data.api.InstanceIdentifier.create(shortened);
324         }
325         return null;
326     }
327
328     private InstanceIdentifier<? extends DataObject> shortenToLastAugment(
329             final InstanceIdentifier<? extends DataObject> binding) {
330         int position = 0;
331         int foundPosition = -1;
332         for (org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : binding.getPathArguments()) {
333             position++;
334             if (isAugmentation(arg.getType())) {
335                 foundPosition = position;
336             }
337         }
338         return InstanceIdentifier.create(Iterables.limit(binding.getPathArguments(), foundPosition));
339     }
340
341     private org.opendaylight.yangtools.yang.data.api.InstanceIdentifier toNormalizedImpl(
342             final InstanceIdentifier<? extends DataObject> binding) {
343         final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier legacyPath = bindingToLegacy
344                 .toDataDom(binding);
345         final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier normalized = legacyToNormalized
346                 .toNormalized(legacyPath);
347         return normalized;
348     }
349
350     @SuppressWarnings("unchecked")
351     private Iterable<Class<? extends DataObject>> getAugmentationChildren(final Class<?> targetType) {
352         List<Class<? extends DataObject>> ret = new LinkedList<>();
353         for (Method method : targetType.getMethods()) {
354             Class<?> entity = getYangModeledType(method);
355             if (entity != null) {
356                 ret.add((Class<? extends DataObject>) entity);
357             }
358         }
359         return ret;
360     }
361
362     @SuppressWarnings({ "rawtypes", "unchecked" })
363     private Class<? extends DataObject> getYangModeledType(final Method method) {
364         if (method.getName().equals("getClass") || !method.getName().startsWith("get")
365                 || method.getParameterTypes().length > 0) {
366             return null;
367         }
368
369         Class<?> returnType = method.getReturnType();
370         if (DataContainer.class.isAssignableFrom(returnType)) {
371             return (Class) returnType;
372         } else if (List.class.isAssignableFrom(returnType)) {
373             try {
374                 return ClassLoaderUtils.withClassLoader(method.getDeclaringClass().getClassLoader(),
375                         new Supplier<Class>() {
376                     @Override
377                     public Class get() {
378                         Type listResult = ClassLoaderUtils.getFirstGenericParameter(method
379                                 .getGenericReturnType());
380                         if (listResult instanceof Class
381                                 && DataObject.class.isAssignableFrom((Class) listResult)) {
382                             return (Class<?>) listResult;
383                         }
384                         return null;
385                     }
386
387                 });
388             } catch (Exception e) {
389                 LOG.debug("Could not get YANG modeled entity for {}", method, e);
390                 return null;
391             }
392
393         }
394         return null;
395     }
396
397     @SuppressWarnings({ "unchecked", "rawtypes" })
398     private static InstanceIdentifier<?> toWildcarded(final InstanceIdentifier<?> orig) {
399         List<org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument> wildArgs = new LinkedList<>();
400         for (org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : orig.getPathArguments()) {
401             wildArgs.add(new Item(arg.getType()));
402         }
403         return InstanceIdentifier.create(wildArgs);
404     }
405
406     private static boolean isAugmentation(final Class<? extends DataObject> type) {
407         return Augmentation.class.isAssignableFrom(type);
408     }
409
410     private static boolean isAugmentationIdentifier(final InstanceIdentifier<?> potential) {
411         return Augmentation.class.isAssignableFrom(potential.getTargetType());
412     }
413
414     private boolean isAugmentationIdentifier(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier processed) {
415         return Iterables.getLast(processed.getPathArguments()) instanceof AugmentationIdentifier;
416     }
417
418     private static int getAugmentationCount(final InstanceIdentifier<?> potential) {
419         int count = 0;
420         for(org.opendaylight.yangtools.yang.binding.InstanceIdentifier.PathArgument arg : potential.getPathArguments()) {
421             if(isAugmentation(arg.getType())) {
422                 count++;
423             }
424
425         }
426         return count;
427     }
428
429     private static int getAugmentationCount(final org.opendaylight.yangtools.yang.data.api.InstanceIdentifier potential) {
430         int count = 0;
431         for(PathArgument arg : potential.getPathArguments()) {
432             if(arg instanceof AugmentationIdentifier) {
433                 count++;
434             }
435         }
436         return count;
437     }
438
439     public Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>>  deserializeFunction(final InstanceIdentifier<?> path) {
440         return new DeserializeFunction(this, path);
441     }
442
443     private static class DeserializeFunction implements Function<Optional<NormalizedNode<?, ?>>, Optional<DataObject>> {
444
445         private final BindingToNormalizedNodeCodec codec;
446         private final InstanceIdentifier<?> path;
447
448         public DeserializeFunction(final BindingToNormalizedNodeCodec codec, final InstanceIdentifier<?> path) {
449             super();
450             this.codec = Preconditions.checkNotNull(codec, "Codec must not be null");
451             this.path = Preconditions.checkNotNull(path, "Path must not be null");
452         }
453
454         @Nullable
455         @Override
456         public Optional<DataObject> apply(@Nullable final Optional<NormalizedNode<?, ?>> normalizedNode) {
457             if (normalizedNode.isPresent()) {
458                 final DataObject dataObject;
459                 try {
460                     dataObject = codec.toBinding(path, normalizedNode.get());
461                 } catch (DeserializationException e) {
462                     LOG.warn("Failed to create dataobject from node {}", normalizedNode.get(), e);
463                     throw new IllegalStateException("Failed to create dataobject", e);
464                 }
465
466                 if (dataObject != null) {
467                     return Optional.of(dataObject);
468                 }
469             }
470             return Optional.absent();
471         }
472     }
473 }

©2013 OpenDaylight, A Linux Foundation Collaborative Project. All Rights Reserved.
OpenDaylight is a registered trademark of The OpenDaylight Project, Inc.
Linux Foundation and OpenDaylight are registered trademarks of the Linux Foundation.
Linux is a registered trademark of Linus Torvalds.