2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.mdsal.binding.dom.codec.impl;
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;
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;
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;
37 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
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();
46 private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
47 private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
48 private final DataObjectCodecContext<D,?> context;
50 private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
51 private volatile Integer cachedHashcode = null;
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");
60 public Object invoke(final Object proxy, final Method method, final Object[] args) {
61 switch (method.getParameterCount()) {
63 switch (method.getName()) {
64 case DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME:
65 return context.getBindingClass();
67 return bindingToString();
69 return bindingHashCode();
71 return getAugmentationsImpl();
73 return getBindingData(method);
76 switch (method.getName()) {
77 case AUGMENTABLE_GET_AUGMENTATION_NAME:
78 return getAugmentationImpl((Class<?>) args[0]);
80 return bindingEquals(args[0]);
89 throw new UnsupportedOperationException("Unsupported method " + method);
92 private boolean bindingEquals(final Object other) {
96 if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
100 for (final Method m : context.getHashCodeAndEqualsMethods()) {
101 final Object thisValue = getBindingData(m);
102 final Object otherValue = m.invoke(other);
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.
107 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
108 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
111 } else if (!Objects.equals(thisValue, otherValue)) {
116 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
117 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
121 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
122 LOG.warn("Can not determine equality of {} and {}", this, other, e);
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);
135 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
138 private Integer bindingHashCode() {
139 final Integer ret = cachedHashcode;
144 final int prime = 31;
146 for (final Method m : context.getHashCodeAndEqualsMethods()) {
147 final Object value = getBindingData(m);
148 result = prime * result + Objects.hashCode(value);
150 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
151 result = prime * result + getAugmentationsImpl().hashCode();
153 cachedHashcode = result;
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) {
164 cached = readedValue;
166 cachedData.putIfAbsent(method, cached);
169 return cached == NULL_VALUE ? null : cached;
172 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
173 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> ret = cachedAugmentations;
175 synchronized (this) {
176 ret = cachedAugmentations;
178 ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
179 cachedAugmentations = ret;
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");
192 return getAugmentationsImpl();
195 private Object getAugmentationImpl(final Class<?> cls) {
196 Preconditions.checkNotNull(cls, "Supplied augmentation must not be null.");
198 final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
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());
222 public String bindingToString() {
223 final ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
225 for (final Method m : context.getHashCodeAndEqualsMethods()) {
226 helper.add(m.getName(), getBindingData(m));
228 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
229 helper.add("augmentations", getAugmentationsImpl());
231 return helper.toString();
235 public int hashCode() {
236 final int prime = 31;
238 result = prime * result + context.hashCode();
239 result = prime * result + data.hashCode();
244 public boolean equals(final Object obj) {
251 if (getClass() != obj.getClass()) {
254 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
255 return Objects.equals(context, other.context) && Objects.equals(data, other.data);