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.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;
38 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
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";
46 private static final @NonNull Object NULL_VALUE = new Object();
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;
54 private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
55 private volatile Integer cachedHashcode = null;
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");
64 public Object invoke(final Object proxy, final Method method, final Object[] args) {
65 switch (method.getParameterCount()) {
67 final String methodName = method.getName();
69 case DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME:
70 return context.getBindingClass();
72 return bindingToString();
74 return bindingHashCode();
76 return getAugmentationsImpl();
78 return getBindingData(methodName);
81 switch (method.getName()) {
82 case AUGMENTABLE_GET_AUGMENTATION_NAME:
83 return getAugmentationImpl((Class<?>) args[0]);
85 return bindingEquals(args[0]);
94 throw new UnsupportedOperationException("Unsupported method " + method);
97 private boolean bindingEquals(final Object other) {
101 if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
105 for (final Method m : context.propertyMethods()) {
106 final Object thisValue = getBindingData(m.getName());
107 final Object otherValue = m.invoke(other);
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.
112 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
113 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
116 } else if (!Objects.equals(thisValue, otherValue)) {
121 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
122 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
126 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
127 LOG.warn("Can not determine equality of {} and {}", this, other, e);
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);
140 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
143 private Integer bindingHashCode() {
144 final Integer cached = cachedHashcode;
145 if (cached != null) {
149 final int prime = 31;
151 for (final Method m : context.propertyMethods()) {
152 final Object value = getBindingData(m.getName());
153 result = prime * result + Objects.hashCode(value);
155 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
156 result = prime * result + getAugmentationsImpl().hashCode();
158 final Integer ret = result;
159 cachedHashcode = ret;
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);
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;
176 private static Object unmaskNull(final @NonNull Object masked) {
177 return masked == NULL_VALUE ? null : masked;
180 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
181 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> ret = cachedAugmentations;
183 synchronized (this) {
184 ret = cachedAugmentations;
186 ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
187 cachedAugmentations = ret;
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");
200 return getAugmentationsImpl();
203 private Object getAugmentationImpl(final Class<?> cls) {
204 Preconditions.checkNotNull(cls, "Supplied augmentation must not be null.");
206 final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
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());
230 public String bindingToString() {
231 final ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
233 for (final Method m : context.propertyMethods()) {
234 final String methodName = m.getName();
235 helper.add(methodName, getBindingData(methodName));
237 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
238 helper.add("augmentations", getAugmentationsImpl());
240 return helper.toString();
244 public int hashCode() {
245 final int prime = 31;
247 result = prime * result + context.hashCode();
248 result = prime * result + data.hashCode();
253 public boolean equals(final Object obj) {
260 if (getClass() != obj.getClass()) {
263 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
264 return Objects.equals(context, other.context) && Objects.equals(data, other.data);