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