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 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_IMPLEMENTED_INTERFACE_NAME;
15 import com.google.common.base.MoreObjects;
16 import com.google.common.base.MoreObjects.ToStringHelper;
17 import com.google.common.collect.ImmutableList;
18 import com.google.common.collect.ImmutableMap;
19 import java.lang.reflect.InvocationHandler;
20 import java.lang.reflect.InvocationTargetException;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.Proxy;
23 import java.util.Arrays;
25 import java.util.Objects;
26 import java.util.Optional;
27 import java.util.concurrent.ConcurrentHashMap;
28 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
29 import org.eclipse.jdt.annotation.NonNull;
30 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
31 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
32 import org.opendaylight.yangtools.yang.binding.Augmentable;
33 import org.opendaylight.yangtools.yang.binding.Augmentation;
34 import org.opendaylight.yangtools.yang.binding.DataObject;
35 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
36 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
38 import org.slf4j.Logger;
39 import org.slf4j.LoggerFactory;
41 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
43 private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
44 private static final String TO_STRING = "toString";
45 private static final String EQUALS = "equals";
46 private static final String HASHCODE = "hashCode";
47 private static final String AUGMENTATIONS = "augmentations";
48 private static final @NonNull Object NULL_VALUE = new Object();
50 // Method.getName() is guaranteed to be interned and all getter methods have zero arguments, name is sufficient to
51 // identify the data, skipping Method.hashCode() computation.
52 private final ConcurrentHashMap<String, Object> cachedData = new ConcurrentHashMap<>();
53 private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
54 private final DataObjectCodecContext<D,?> context;
56 @SuppressWarnings("rawtypes")
57 private static final AtomicReferenceFieldUpdater<LazyDataObject, ImmutableMap> CACHED_AUGMENTATIONS_UPDATER =
58 AtomicReferenceFieldUpdater.newUpdater(LazyDataObject.class, ImmutableMap.class, "cachedAugmentations");
59 private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
60 private volatile Integer cachedHashcode = null;
62 @SuppressWarnings({ "rawtypes", "unchecked" })
63 LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
64 this.context = requireNonNull(ctx, "Context must not be null");
65 this.data = requireNonNull(data, "Data must not be null");
69 public Object invoke(final Object proxy, final Method method, final Object[] args) {
70 switch (method.getParameterCount()) {
72 final String methodName = method.getName();
74 case DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME:
75 return context.getBindingClass();
77 return bindingToString();
79 return bindingHashCode();
81 return getAugmentationsImpl();
83 return method.isDefault() ? nonnullBindingData(methodName) : getBindingData(methodName);
86 switch (method.getName()) {
87 case AUGMENTABLE_AUGMENTATION_NAME:
88 return getAugmentationImpl((Class<?>) args[0]);
90 return bindingEquals(args[0]);
99 throw new UnsupportedOperationException("Unsupported method " + method);
102 private boolean bindingEquals(final Object other) {
106 final Class<D> bindingClass = context.getBindingClass();
107 if (!bindingClass.isAssignableFrom(other.getClass())) {
111 for (final Method m : context.propertyMethods()) {
112 final Object thisValue = getBindingData(m.getName());
113 final Object otherValue = m.invoke(other);
115 * added for valid byte array comparison, when list key type is binary
116 * deepEquals is not used since it does excessive amount of instanceof calls.
118 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
119 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
122 } else if (!Objects.equals(thisValue, otherValue)) {
127 if (Augmentable.class.isAssignableFrom(bindingClass)) {
128 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
132 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
133 LOG.warn("Can not determine equality of {} and {}", this, other, e);
139 private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
140 if (dataObject instanceof AugmentationReader) {
141 return ((AugmentationReader) dataObject).getAugmentations(dataObject);
142 } else if (dataObject instanceof Augmentable<?>) {
143 return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
146 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
149 private Integer bindingHashCode() {
150 final Integer cached = cachedHashcode;
151 if (cached != null) {
155 final int prime = 31;
157 for (final Method m : context.propertyMethods()) {
158 final Object value = getBindingData(m.getName());
159 result = prime * result + Objects.hashCode(value);
161 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
162 result = prime * result + getAugmentationsImpl().hashCode();
164 final Integer ret = result;
165 cachedHashcode = ret;
169 private Object nonnullBindingData(final String methodName) {
170 final Object value = getBindingData(context.getterNameForNonnullName(methodName));
171 return value != null ? value : ImmutableList.of();
174 // Internal invocation, can only target getFoo() methods
175 private Object getBindingData(final String methodName) {
176 final Object cached = cachedData.get(methodName);
177 if (cached != null) {
178 return unmaskNull(cached);
181 final Object value = context.getBindingChildValue(methodName, data);
182 final Object raced = cachedData.putIfAbsent(methodName, value == null ? NULL_VALUE : value);
183 // If we raced we need to return previously-stored value
184 return raced != null ? unmaskNull(raced) : value;
187 private static Object unmaskNull(final @NonNull Object masked) {
188 return masked == NULL_VALUE ? null : masked;
191 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
192 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> local = cachedAugmentations;
197 local = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
198 return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
202 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
203 checkArgument(this == Proxy.getInvocationHandler(obj),
204 "Supplied object is not associated with this proxy handler");
206 return getAugmentationsImpl();
209 private Object getAugmentationImpl(final Class<?> cls) {
210 requireNonNull(cls, "Supplied augmentation must not be null.");
212 final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
217 @SuppressWarnings({"unchecked","rawtypes"})
218 final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild((Class) cls);
219 if (optAugCtx.isPresent()) {
220 final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
221 // Due to binding specification not representing grouping instantiations we can end up having the same
222 // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
223 // are still represented by distinct binding classes and therefore we need to make sure the result matches
224 // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
225 // ClassCastException.
226 if (cls.isAssignableFrom(augCtx.getBindingClass())) {
227 final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
228 if (augData.isPresent()) {
229 return augCtx.deserialize(augData.get());
236 public String bindingToString() {
237 final Class<D> bindingClass = context.getBindingClass();
238 final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
240 for (final Method m : context.propertyMethods()) {
241 final String methodName = m.getName();
242 helper.add(methodName, getBindingData(methodName));
244 if (Augmentable.class.isAssignableFrom(bindingClass)) {
245 helper.add("augmentations", getAugmentationsImpl());
247 return helper.toString();
251 public int hashCode() {
252 final int prime = 31;
254 result = prime * result + context.hashCode();
255 result = prime * result + data.hashCode();
260 public boolean equals(final Object obj) {
267 if (getClass() != obj.getClass()) {
270 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
271 return Objects.equals(context, other.context) && Objects.equals(data, other.data);