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