e191054a7ea0dc8f878e3e28aab56e1ca6f3de2b
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / LazyDataObject.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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
12 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME;
13 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME;
14
15 import com.google.common.base.MoreObjects;
16 import com.google.common.base.MoreObjects.ToStringHelper;
17 import com.google.common.collect.ImmutableMap;
18 import java.lang.reflect.InvocationHandler;
19 import java.lang.reflect.InvocationTargetException;
20 import java.lang.reflect.Method;
21 import java.lang.reflect.Proxy;
22 import java.util.Arrays;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26 import java.util.concurrent.ConcurrentHashMap;
27 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
28 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
29 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
30 import org.opendaylight.yangtools.yang.binding.Augmentable;
31 import org.opendaylight.yangtools.yang.binding.Augmentation;
32 import org.opendaylight.yangtools.yang.binding.DataObject;
33 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
34 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
35 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38
39 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
40
41     private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
42     private static final String TO_STRING = "toString";
43     private static final String EQUALS = "equals";
44     private static final String HASHCODE = "hashCode";
45     private static final String AUGMENTATIONS = "augmentations";
46     private static final Object NULL_VALUE = new Object();
47
48     private final ConcurrentHashMap<String, Object> cachedData = new ConcurrentHashMap<>();
49     private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
50     private final DataObjectCodecContext<D,?> context;
51
52     @SuppressWarnings("rawtypes")
53     private static final AtomicReferenceFieldUpdater<LazyDataObject, ImmutableMap> CACHED_AUGMENTATIONS_UPDATER =
54             AtomicReferenceFieldUpdater.newUpdater(LazyDataObject.class, ImmutableMap.class, "cachedAugmentations");
55     private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
56     private volatile Integer cachedHashcode = null;
57
58     @SuppressWarnings({ "rawtypes", "unchecked" })
59     LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
60         this.context = requireNonNull(ctx, "Context must not be null");
61         this.data = requireNonNull(data, "Data must not be null");
62     }
63
64     @Override
65     public Object invoke(final Object proxy, final Method method, final Object[] args) {
66         switch (method.getParameterCount()) {
67             case 0:
68                 switch (method.getName()) {
69                     case DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME:
70                         return context.getBindingClass();
71                     case TO_STRING:
72                         return bindingToString();
73                     case HASHCODE:
74                         return bindingHashCode();
75                     case AUGMENTATIONS:
76                         return getAugmentationsImpl();
77                     default:
78                         return getBindingData(method);
79                 }
80             case 1:
81                 switch (method.getName()) {
82                     case AUGMENTABLE_AUGMENTATION_NAME:
83                         return getAugmentationImpl((Class<?>) args[0]);
84                     case EQUALS:
85                         return bindingEquals(args[0]);
86                     default:
87                         break;
88                 }
89                 break;
90             default:
91                 break;
92         }
93
94         throw new UnsupportedOperationException("Unsupported method " + method);
95     }
96
97     private boolean bindingEquals(final Object other) {
98         if (other == null) {
99             return false;
100         }
101         final Class<D> bindingClass = context.getBindingClass();
102         if (!bindingClass.isAssignableFrom(other.getClass())) {
103             return false;
104         }
105         try {
106             for (final Method m : context.getHashCodeAndEqualsMethods()) {
107                 final Object thisValue = getBindingData(m);
108                 final Object otherValue = m.invoke(other);
109                 /*
110                 *   added for valid byte array comparison, when list key type is binary
111                 *   deepEquals is not used since it does excessive amount of instanceof calls.
112                 */
113                 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
114                     if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
115                         return false;
116                     }
117                 } else if (!Objects.equals(thisValue, otherValue)) {
118                     return false;
119                 }
120             }
121
122             if (Augmentable.class.isAssignableFrom(bindingClass)) {
123                 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
124                     return false;
125                 }
126             }
127         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
128             LOG.warn("Can not determine equality of {} and {}", this, other, e);
129             return false;
130         }
131         return true;
132     }
133
134     private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
135         if (dataObject instanceof AugmentationReader) {
136             return ((AugmentationReader) dataObject).getAugmentations(dataObject);
137         } else if (dataObject instanceof Augmentable<?>) {
138             return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
139         }
140
141         throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
142     }
143
144     private Integer bindingHashCode() {
145         final Integer cached = cachedHashcode;
146         if (cached != null) {
147             return cached;
148         }
149
150         final int prime = 31;
151         int result = 1;
152         for (final Method m : context.getHashCodeAndEqualsMethods()) {
153             final Object value = getBindingData(m);
154             result = prime * result + Objects.hashCode(value);
155         }
156         if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
157             result = prime * result + getAugmentationsImpl().hashCode();
158         }
159         final Integer ret = result;
160         cachedHashcode = ret;
161         return ret;
162     }
163
164     private Object getBindingData(final Method method) {
165         // Guaranteed to be interned and since method has zero arguments, name is sufficient to identify the data,
166         // skipping Method.hashCode() computation.
167         final String methodName = method.getName();
168         Object cached = cachedData.get(methodName);
169         if (cached == null) {
170             final Object readedValue = context.getBindingChildValue(method, data);
171             cached = readedValue == null ? NULL_VALUE : readedValue;
172
173             final Object raced = cachedData.putIfAbsent(methodName, cached);
174             if (raced != null) {
175                 // Load/store raced, we should return the stored value
176                 cached = raced;
177             }
178         }
179
180         return cached == NULL_VALUE ? null : cached;
181     }
182
183     private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
184         ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> local = cachedAugmentations;
185         if (local != null) {
186             return local;
187         }
188
189         local = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
190         return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
191     }
192
193     @Override
194     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
195         checkArgument(this == Proxy.getInvocationHandler(obj),
196                 "Supplied object is not associated with this proxy handler");
197
198         return getAugmentationsImpl();
199     }
200
201     private Object getAugmentationImpl(final Class<?> cls) {
202         requireNonNull(cls, "Supplied augmentation must not be null.");
203
204         final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
205         if (aug != null) {
206             return aug.get(cls);
207         }
208
209         @SuppressWarnings({"unchecked","rawtypes"})
210         final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild((Class) cls);
211         if (optAugCtx.isPresent()) {
212             final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
213             // Due to binding specification not representing grouping instantiations we can end up having the same
214             // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
215             // are still represented by distinct binding classes and therefore we need to make sure the result matches
216             // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
217             // ClassCastException.
218             if (cls.isAssignableFrom(augCtx.getBindingClass())) {
219                 final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
220                 if (augData.isPresent()) {
221                     return augCtx.deserialize(augData.get());
222                 }
223             }
224         }
225         return null;
226     }
227
228     public String bindingToString() {
229         final Class<D> bindingClass = context.getBindingClass();
230         final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
231
232         for (final Method m : context.getHashCodeAndEqualsMethods()) {
233             helper.add(m.getName(), getBindingData(m));
234         }
235         if (Augmentable.class.isAssignableFrom(bindingClass)) {
236             helper.add("augmentations", getAugmentationsImpl());
237         }
238         return helper.toString();
239     }
240
241     @Override
242     public int hashCode() {
243         final int prime = 31;
244         int result = 1;
245         result = prime * result + context.hashCode();
246         result = prime * result + data.hashCode();
247         return result;
248     }
249
250     @Override
251     public boolean equals(final Object obj) {
252         if (this == obj) {
253             return true;
254         }
255         if (obj == null) {
256             return false;
257         }
258         if (getClass() != obj.getClass()) {
259             return false;
260         }
261         final LazyDataObject<?> other = (LazyDataObject<?>) obj;
262         return Objects.equals(context, other.context) && Objects.equals(data, other.data);
263     }
264 }