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