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