Use Method.getParameterCount()
[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<Method, 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         if (method.getParameterCount() == 0) {
67             final String name = method.getName();
68             if (DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME.equals(name)) {
69                 return context.getBindingClass();
70             } else if (TO_STRING.equals(name)) {
71                 return bindingToString();
72             } else if (HASHCODE.equals(name)) {
73                 return bindingHashCode();
74             } else if (AUGMENTATIONS.equals(name)) {
75                 return getAugmentationsImpl();
76             }
77             return getBindingData(method);
78         } else if (AUGMENTABLE_AUGMENTATION_NAME.equals(method.getName())) {
79             return getAugmentationImpl((Class<?>) args[0]);
80         } else if (EQUALS.equals(method.getName())) {
81             return bindingEquals(args[0]);
82         }
83         throw new UnsupportedOperationException("Unsupported method " + method);
84     }
85
86     private boolean bindingEquals(final Object other) {
87         if (other == null) {
88             return false;
89         }
90         final Class<D> bindingClass = context.getBindingClass();
91         if (!bindingClass.isAssignableFrom(other.getClass())) {
92             return false;
93         }
94         try {
95             for (final Method m : context.getHashCodeAndEqualsMethods()) {
96                 final Object thisValue = getBindingData(m);
97                 final Object otherValue = m.invoke(other);
98                 /*
99                 *   added for valid byte array comparison, when list key type is binary
100                 *   deepEquals is not used since it does excessive amount of instanceof calls.
101                 */
102                 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
103                     if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
104                         return false;
105                     }
106                 } else if (!Objects.equals(thisValue, otherValue)) {
107                     return false;
108                 }
109             }
110
111             if (Augmentable.class.isAssignableFrom(bindingClass)) {
112                 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
113                     return false;
114                 }
115             }
116         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
117             LOG.warn("Can not determine equality of {} and {}", this, other, e);
118             return false;
119         }
120         return true;
121     }
122
123     private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
124         if (dataObject instanceof AugmentationReader) {
125             return ((AugmentationReader) dataObject).getAugmentations(dataObject);
126         } else if (dataObject instanceof Augmentable<?>) {
127             return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
128         }
129
130         throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
131     }
132
133     private Integer bindingHashCode() {
134         final Integer ret = cachedHashcode;
135         if (ret != null) {
136             return ret;
137         }
138
139         final int prime = 31;
140         int result = 1;
141         for (final Method m : context.getHashCodeAndEqualsMethods()) {
142             final Object value = getBindingData(m);
143             result = prime * result + Objects.hashCode(value);
144         }
145         if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
146             result = prime * result + getAugmentationsImpl().hashCode();
147         }
148         cachedHashcode = result;
149         return result;
150     }
151
152     private Object getBindingData(final Method method) {
153         Object cached = cachedData.get(method);
154         if (cached == null) {
155             final Object readedValue = context.getBindingChildValue(method, data);
156             cached = readedValue == null ? NULL_VALUE : readedValue;
157
158             final Object raced = cachedData.putIfAbsent(method, cached);
159             if (raced != null) {
160                 // Load/store raced, we should return the stored value
161                 cached = raced;
162             }
163         }
164
165         return cached == NULL_VALUE ? null : cached;
166     }
167
168     private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
169         ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> local = cachedAugmentations;
170         if (local != null) {
171             return local;
172         }
173
174         local = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
175         return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
176     }
177
178     @Override
179     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
180         checkArgument(this == Proxy.getInvocationHandler(obj),
181                 "Supplied object is not associated with this proxy handler");
182
183         return getAugmentationsImpl();
184     }
185
186     private Object getAugmentationImpl(final Class<?> cls) {
187         requireNonNull(cls, "Supplied augmentation must not be null.");
188
189         final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
190         if (aug != null) {
191             return aug.get(cls);
192         }
193
194         @SuppressWarnings({"unchecked","rawtypes"})
195         final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild((Class) cls);
196         if (optAugCtx.isPresent()) {
197             final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
198             // Due to binding specification not representing grouping instantiations we can end up having the same
199             // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
200             // are still represented by distinct binding classes and therefore we need to make sure the result matches
201             // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
202             // ClassCastException.
203             if (cls.isAssignableFrom(augCtx.getBindingClass())) {
204                 final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
205                 if (augData.isPresent()) {
206                     return augCtx.deserialize(augData.get());
207                 }
208             }
209         }
210         return null;
211     }
212
213     public String bindingToString() {
214         final Class<D> bindingClass = context.getBindingClass();
215         final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
216
217         for (final Method m : context.getHashCodeAndEqualsMethods()) {
218             helper.add(m.getName(), getBindingData(m));
219         }
220         if (Augmentable.class.isAssignableFrom(bindingClass)) {
221             helper.add("augmentations", getAugmentationsImpl());
222         }
223         return helper.toString();
224     }
225
226     @Override
227     public int hashCode() {
228         final int prime = 31;
229         int result = 1;
230         result = prime * result + context.hashCode();
231         result = prime * result + data.hashCode();
232         return result;
233     }
234
235     @Override
236     public boolean equals(final Object obj) {
237         if (this == obj) {
238             return true;
239         }
240         if (obj == null) {
241             return false;
242         }
243         if (getClass() != obj.getClass()) {
244             return false;
245         }
246         final LazyDataObject<?> other = (LazyDataObject<?>) obj;
247         return Objects.equals(context, other.context) && Objects.equals(data, other.data);
248     }
249 }