Switch to using VarHandles
[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.ImmutableMap;
14 import java.lang.invoke.MethodHandles;
15 import java.lang.invoke.VarHandle;
16 import java.util.Map;
17 import java.util.Optional;
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 static final VarHandle CACHED_AUGMENTATIONS;
38
39     static {
40         try {
41             CACHED_AUGMENTATIONS = MethodHandles.lookup().findVarHandle(AugmentableCodecDataObject.class,
42                 "cachedAugmentations", ImmutableMap.class);
43         } catch (ReflectiveOperationException e) {
44             throw new ExceptionInInitializerError(e);
45         }
46     }
47
48     // Used via VarHandle
49     @SuppressWarnings("unused")
50     private volatile ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> cachedAugmentations;
51
52     protected AugmentableCodecDataObject(final DataObjectCodecContext<T, ?> context,
53             final NormalizedNodeContainer<?, ?, ?> data) {
54         super(context, data);
55     }
56
57     @SuppressWarnings("unchecked")
58     @Override
59     public final <A extends Augmentation<T>> @Nullable A augmentation(final Class<A> augmentationType) {
60         requireNonNull(augmentationType, "Supplied augmentation must not be null.");
61
62         final ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> aug = acquireAugmentations();
63         if (aug != null) {
64             return (A) aug.get(augmentationType);
65         }
66
67         @SuppressWarnings("rawtypes")
68         final Optional<DataContainerCodecContext<?, ?>> optAugCtx = codecContext().possibleStreamChild(
69             (Class) augmentationType);
70         if (optAugCtx.isPresent()) {
71             final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
72             // Due to binding specification not representing grouping instantiations we can end up having the same
73             // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
74             // are still represented by distinct binding classes and therefore we need to make sure the result matches
75             // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
76             // ClassCastException.
77             if (augmentationType.isAssignableFrom(augCtx.getBindingClass())) {
78                 final Optional<NormalizedNode<?, ?>> augData = codecData().getChild(augCtx.getDomPathArgument());
79                 if (augData.isPresent()) {
80                     return (A) augCtx.deserialize(augData.get());
81                 }
82             }
83         }
84         return null;
85     }
86
87     @Override
88     public final ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> augmentations() {
89         final ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> local = acquireAugmentations();
90         return local != null ? local : loadAugmentations();
91     }
92
93     @Override
94     final int codecAugmentedHashCode() {
95         return 31 * super.codecAugmentedHashCode() + augmentations().hashCode();
96     }
97
98     @Override
99     final boolean codecAugmentedEquals(final T other) {
100         return super.codecAugmentedEquals(other) && augmentations().equals(getAllAugmentations(other));
101     }
102
103     @Override
104     final ToStringHelper codecAugmentedFillToString(final ToStringHelper helper) {
105         return super.codecAugmentedFillToString(helper).add("augmentation", augmentations().values());
106     }
107
108     private ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> acquireAugmentations() {
109         return (ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>>) CACHED_AUGMENTATIONS.getAcquire(this);
110     }
111
112     @SuppressWarnings("unchecked")
113     private ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> loadAugmentations() {
114         final ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>> ret = ImmutableMap.copyOf(
115             codecContext().getAllAugmentationsFrom(codecData()));
116         final Object witness = CACHED_AUGMENTATIONS.compareAndExchangeRelease(this, null, ret);
117         return witness == null ? ret : (ImmutableMap<Class<? extends Augmentation<T>>, Augmentation<T>>) witness;
118     }
119
120     private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(
121             final Augmentable<?> dataObject) {
122         return dataObject instanceof AugmentationReader ? ((AugmentationReader) dataObject).getAugmentations(dataObject)
123                 : BindingReflections.getAugmentations(dataObject);
124     }
125 }