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