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