Cache NodeContextSuppliers in CodecDataObject
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / AugmentableCodecDataObject.java
1 /*
2  * Copyright (c) 2019 PANTHEON.tech, 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 package org.opendaylight.mdsal.binding.dom.codec.impl;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.base.MoreObjects.ToStringHelper;
13 import com.google.common.collect.ImmutableClassToInstanceMap;
14 import java.util.Map;
15 import java.util.Optional;
16 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.eclipse.jdt.annotation.Nullable;
19 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
20 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
21 import org.opendaylight.yangtools.yang.binding.Augmentable;
22 import org.opendaylight.yangtools.yang.binding.Augmentation;
23 import org.opendaylight.yangtools.yang.binding.AugmentationHolder;
24 import org.opendaylight.yangtools.yang.binding.DataObject;
25 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
26 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
27
28 /**
29  * A base class for {@link DataObject}s which are also {@link Augmentable}, backed by {@link DataObjectCodecContext}.
30  * While this class is public, it not part of API surface and is an implementation detail. The only reason for it being
31  * public is that it needs to be accessible by code generated at runtime.
32  *
33  * @param <T> DataObject type
34  */
35 public abstract class AugmentableCodecDataObject<T extends DataObject & Augmentable<T>>
36         extends CodecDataObject<T> implements Augmentable<T>, AugmentationHolder<T> {
37     private final @NonNull DataObjectCodecContext<T, ?> context;
38
39     @SuppressWarnings("rawtypes")
40     private static final AtomicReferenceFieldUpdater<AugmentableCodecDataObject, ImmutableClassToInstanceMap>
41             CACHED_AUGMENTATIONS_UPDATER = AtomicReferenceFieldUpdater.newUpdater(AugmentableCodecDataObject.class,
42                 ImmutableClassToInstanceMap.class, "cachedAugmentations");
43     private volatile ImmutableClassToInstanceMap<Augmentation<T>> cachedAugmentations;
44
45     public AugmentableCodecDataObject(final DataObjectCodecContext<T, ?> context,
46             final NormalizedNodeContainer<?, ?, ?> data) {
47         super(data);
48         this.context = requireNonNull(context, "Context must not be null");
49     }
50
51     @Override
52     public final <A extends Augmentation<T>> @Nullable A augmentation(final Class<A> augmentationType) {
53         requireNonNull(augmentationType, "Supplied augmentation must not be null.");
54
55         final ImmutableClassToInstanceMap<Augmentation<T>> aug = cachedAugmentations;
56         if (aug != null) {
57             return aug.getInstance(augmentationType);
58         }
59
60         @SuppressWarnings({"unchecked","rawtypes"})
61         final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild(
62             (Class) augmentationType);
63         if (optAugCtx.isPresent()) {
64             final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
65             // Due to binding specification not representing grouping instantiations we can end up having the same
66             // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
67             // are still represented by distinct binding classes and therefore we need to make sure the result matches
68             // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
69             // ClassCastException.
70             if (augmentationType.isAssignableFrom(augCtx.getBindingClass())) {
71                 final Optional<NormalizedNode<?, ?>> augData = codecData().getChild(augCtx.getDomPathArgument());
72                 if (augData.isPresent()) {
73                     return (A) augCtx.deserialize(augData.get());
74                 }
75             }
76         }
77         return null;
78     }
79
80     @Override
81     public final Map<Class<? extends Augmentation<T>>, Augmentation<T>> augmentations() {
82         ImmutableClassToInstanceMap<Augmentation<T>> local = cachedAugmentations;
83         if (local != null) {
84             return local;
85         }
86
87         local = ImmutableClassToInstanceMap.copyOf(context.getAllAugmentationsFrom(codecData()));
88         return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
89     }
90
91     @Override
92     final int codecAugmentedHashCode() {
93         return 31 * super.codecAugmentedHashCode() + augmentations().hashCode();
94     }
95
96     @Override
97     final boolean codecAugmentedEquals(final T other) {
98         return super.codecAugmentedEquals(other) && augmentations().equals(getAllAugmentations(other));
99     }
100
101     @Override
102     final ToStringHelper codecAugmentedFillToString(final ToStringHelper helper) {
103         return super.codecAugmentedFillToString(helper).add("augmentations", augmentations());
104     }
105
106     private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(
107             final Augmentable<?> dataObject) {
108         if (dataObject instanceof AugmentationReader) {
109             return ((AugmentationReader) dataObject).getAugmentations(dataObject);
110         }
111         return BindingReflections.getAugmentations(dataObject);
112     }
113 }