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