0c7a16586c9e566d43e07833eda750cbdbde67d3
[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.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import java.lang.reflect.InvocationHandler;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.Proxy;
18 import java.util.Arrays;
19 import java.util.Map;
20 import java.util.Objects;
21 import java.util.Optional;
22 import java.util.concurrent.ConcurrentHashMap;
23 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
24 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
25 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
26 import org.opendaylight.yangtools.yang.binding.Augmentable;
27 import org.opendaylight.yangtools.yang.binding.Augmentation;
28 import org.opendaylight.yangtools.yang.binding.DataObject;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
34
35 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
36
37     private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
38     private static final String GET_IMPLEMENTED_INTERFACE = "getImplementedInterface";
39     private static final String TO_STRING = "toString";
40     private static final String EQUALS = "equals";
41     private static final String HASHCODE = "hashCode";
42     private static final String AUGMENTATIONS = "augmentations";
43     private static final Object NULL_VALUE = new Object();
44
45     private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
46     private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
47     private final DataObjectCodecContext<D,?> context;
48
49     private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
50     private volatile Integer cachedHashcode = null;
51
52     @SuppressWarnings({ "rawtypes", "unchecked" })
53     LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
54         this.context = Preconditions.checkNotNull(ctx, "Context must not be null");
55         this.data = Preconditions.checkNotNull(data, "Data must not be null");
56     }
57
58     @Override
59     public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
60         if (method.getParameterTypes().length == 0) {
61             final String name = method.getName();
62             if (GET_IMPLEMENTED_INTERFACE.equals(name)) {
63                 return context.getBindingClass();
64             } else if (TO_STRING.equals(name)) {
65                 return bindingToString();
66             } else if (HASHCODE.equals(name)) {
67                 return bindingHashCode();
68             } else if (AUGMENTATIONS.equals(name)) {
69                 return getAugmentationsImpl();
70             }
71             return getBindingData(method);
72         } else if (BindingMapping.AUGMENTABLE_AUGMENTATION_NAME.equals(method.getName())) {
73             return getAugmentationImpl((Class<?>) args[0]);
74         } else if (EQUALS.equals(method.getName())) {
75             return bindingEquals(args[0]);
76         }
77         throw new UnsupportedOperationException("Unsupported method " + method);
78     }
79
80     private boolean bindingEquals(final Object other) {
81         if (other == null) {
82             return false;
83         }
84         if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
85             return false;
86         }
87         try {
88             for (final Method m : context.getHashCodeAndEqualsMethods()) {
89                 final Object thisValue = getBindingData(m);
90                 final Object otherValue = m.invoke(other);
91                 /*
92                 *   added for valid byte array comparison, when list key type is binary
93                 *   deepEquals is not used since it does excessive amount of instanceof calls.
94                 */
95                 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
96                     if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
97                         return false;
98                     }
99                 } else if (!Objects.equals(thisValue, otherValue)) {
100                     return false;
101                 }
102             }
103
104             if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
105                 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
106                     return false;
107                 }
108             }
109         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
110             LOG.warn("Can not determine equality of {} and {}", this, other, e);
111             return false;
112         }
113         return true;
114     }
115
116     private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
117         if (dataObject instanceof AugmentationReader) {
118             return ((AugmentationReader) dataObject).getAugmentations(dataObject);
119         } else if (dataObject instanceof Augmentable<?>) {
120             return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
121         }
122
123         throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
124     }
125
126     private Integer bindingHashCode() {
127         final Integer ret = cachedHashcode;
128         if (ret != null) {
129             return ret;
130         }
131
132         final int prime = 31;
133         int result = 1;
134         for (final Method m : context.getHashCodeAndEqualsMethods()) {
135             final Object value = getBindingData(m);
136             result = prime * result + Objects.hashCode(value);
137         }
138         if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
139             result = prime * result + getAugmentationsImpl().hashCode();
140         }
141         cachedHashcode = result;
142         return result;
143     }
144
145     private Object getBindingData(final Method method) {
146         Object cached = cachedData.get(method);
147         if (cached == null) {
148             final Object readedValue = context.getBindingChildValue(method, data);
149             if (readedValue == null) {
150                 cached = NULL_VALUE;
151             } else {
152                 cached = readedValue;
153             }
154             cachedData.putIfAbsent(method, cached);
155         }
156
157         return cached == NULL_VALUE ? null : cached;
158     }
159
160     private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
161         ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> ret = cachedAugmentations;
162         if (ret == null) {
163             synchronized (this) {
164                 ret = cachedAugmentations;
165                 if (ret == null) {
166                     ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
167                     cachedAugmentations = ret;
168                 }
169             }
170         }
171
172         return ret;
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 ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
212
213         for (final Method m : context.getHashCodeAndEqualsMethods()) {
214             helper.add(m.getName(), getBindingData(m));
215         }
216         if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
217             helper.add("augmentations", getAugmentationsImpl());
218         }
219         return helper.toString();
220     }
221
222     @Override
223     public int hashCode() {
224         final int prime = 31;
225         int result = 1;
226         result = prime * result + context.hashCode();
227         result = prime * result + data.hashCode();
228         return result;
229     }
230
231     @Override
232     public boolean equals(final Object obj) {
233         if (this == obj) {
234             return true;
235         }
236         if (obj == null) {
237             return false;
238         }
239         if (getClass() != obj.getClass()) {
240             return false;
241         }
242         final LazyDataObject<?> other = (LazyDataObject<?>) obj;
243         return Objects.equals(context, other.context) && Objects.equals(data, other.data);
244     }
245 }