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