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_GET_IMPLEMENTED_INTERFACE_NAME;
14 import static org.opendaylight.mdsal.binding.spec.naming.BindingMapping.DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME;
16 import com.google.common.base.MoreObjects;
17 import com.google.common.base.MoreObjects.ToStringHelper;
18 import com.google.common.collect.ImmutableList;
19 import com.google.common.collect.ImmutableMap;
20 import java.lang.reflect.InvocationHandler;
21 import java.lang.reflect.InvocationTargetException;
22 import java.lang.reflect.Method;
23 import java.lang.reflect.Proxy;
24 import java.util.Arrays;
26 import java.util.Objects;
27 import java.util.Optional;
28 import java.util.concurrent.ConcurrentHashMap;
29 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
30 import org.eclipse.jdt.annotation.NonNull;
31 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
32 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
33 import org.opendaylight.yangtools.yang.binding.Augmentable;
34 import org.opendaylight.yangtools.yang.binding.Augmentation;
35 import org.opendaylight.yangtools.yang.binding.DataObject;
36 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
37 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
38 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
42 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
44 private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
45 private static final String TO_STRING = "toString";
46 private static final String EQUALS = "equals";
47 private static final String HASHCODE = "hashCode";
48 private static final String AUGMENTATIONS = "augmentations";
49 private static final @NonNull Object NULL_VALUE = new Object();
51 // Method.getName() is guaranteed to be interned and all getter methods have zero arguments, name is sufficient to
52 // identify the data, skipping Method.hashCode() computation.
53 private final ConcurrentHashMap<String, Object> cachedData = new ConcurrentHashMap<>();
54 private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
55 private final DataObjectCodecContext<D,?> context;
57 @SuppressWarnings("rawtypes")
58 private static final AtomicReferenceFieldUpdater<LazyDataObject, ImmutableMap> CACHED_AUGMENTATIONS_UPDATER =
59 AtomicReferenceFieldUpdater.newUpdater(LazyDataObject.class, ImmutableMap.class, "cachedAugmentations");
60 private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
61 private volatile Integer cachedHashcode = null;
63 @SuppressWarnings({ "rawtypes", "unchecked" })
64 LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
65 this.context = requireNonNull(ctx, "Context must not be null");
66 this.data = requireNonNull(data, "Data must not be null");
70 public Object invoke(final Object proxy, final Method method, final Object[] args) {
71 switch (method.getParameterCount()) {
73 final String methodName = method.getName();
75 case DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME:
76 case DATA_CONTAINER_IMPLEMENTED_INTERFACE_NAME:
77 return context.getBindingClass();
79 return bindingToString();
81 return bindingHashCode();
83 return getAugmentationsImpl();
85 return method.isDefault() ? nonnullBindingData(methodName) : getBindingData(methodName);
88 switch (method.getName()) {
89 case AUGMENTABLE_AUGMENTATION_NAME:
90 return getAugmentationImpl((Class<?>) args[0]);
92 return bindingEquals(args[0]);
101 throw new UnsupportedOperationException("Unsupported method " + method);
104 private boolean bindingEquals(final Object other) {
108 final Class<D> bindingClass = context.getBindingClass();
109 if (!bindingClass.isAssignableFrom(other.getClass())) {
113 for (final Method m : context.propertyMethods()) {
114 final Object thisValue = getBindingData(m.getName());
115 final Object otherValue = m.invoke(other);
117 * added for valid byte array comparison, when list key type is binary
118 * deepEquals is not used since it does excessive amount of instanceof calls.
120 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
121 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
124 } else if (!Objects.equals(thisValue, otherValue)) {
129 if (Augmentable.class.isAssignableFrom(bindingClass)) {
130 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
134 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
135 LOG.warn("Can not determine equality of {} and {}", this, other, e);
141 private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
142 if (dataObject instanceof AugmentationReader) {
143 return ((AugmentationReader) dataObject).getAugmentations(dataObject);
144 } else if (dataObject instanceof Augmentable<?>) {
145 return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
148 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
151 private Integer bindingHashCode() {
152 final Integer cached = cachedHashcode;
153 if (cached != null) {
157 final int prime = 31;
159 for (final Method m : context.propertyMethods()) {
160 final Object value = getBindingData(m.getName());
161 result = prime * result + Objects.hashCode(value);
163 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
164 result = prime * result + getAugmentationsImpl().hashCode();
166 final Integer ret = result;
167 cachedHashcode = ret;
171 private Object nonnullBindingData(final String methodName) {
172 final Object value = getBindingData(context.getterNameForNonnullName(methodName));
173 return value != null ? value : ImmutableList.of();
176 // Internal invocation, can only target getFoo() methods
177 private Object getBindingData(final String methodName) {
178 final Object cached = cachedData.get(methodName);
179 if (cached != null) {
180 return unmaskNull(cached);
183 final Object value = context.getBindingChildValue(methodName, data);
184 final Object raced = cachedData.putIfAbsent(methodName, value == null ? NULL_VALUE : value);
185 // If we raced we need to return previously-stored value
186 return raced != null ? unmaskNull(raced) : value;
189 private static Object unmaskNull(final @NonNull Object masked) {
190 return masked == NULL_VALUE ? null : masked;
193 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
194 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> local = cachedAugmentations;
199 local = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
200 return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
204 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
205 checkArgument(this == Proxy.getInvocationHandler(obj),
206 "Supplied object is not associated with this proxy handler");
208 return getAugmentationsImpl();
211 private Object getAugmentationImpl(final Class<?> cls) {
212 requireNonNull(cls, "Supplied augmentation must not be null.");
214 final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
219 @SuppressWarnings({"unchecked","rawtypes"})
220 final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild((Class) cls);
221 if (optAugCtx.isPresent()) {
222 final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
223 // Due to binding specification not representing grouping instantiations we can end up having the same
224 // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
225 // are still represented by distinct binding classes and therefore we need to make sure the result matches
226 // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
227 // ClassCastException.
228 if (cls.isAssignableFrom(augCtx.getBindingClass())) {
229 final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
230 if (augData.isPresent()) {
231 return augCtx.deserialize(augData.get());
238 public String bindingToString() {
239 final Class<D> bindingClass = context.getBindingClass();
240 final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
242 for (final Method m : context.propertyMethods()) {
243 final String methodName = m.getName();
244 helper.add(methodName, getBindingData(methodName));
246 if (Augmentable.class.isAssignableFrom(bindingClass)) {
247 helper.add("augmentations", getAugmentationsImpl());
249 return helper.toString();
253 public int hashCode() {
254 final int prime = 31;
256 result = prime * result + context.hashCode();
257 result = prime * result + data.hashCode();
262 public boolean equals(final Object obj) {
269 if (getClass() != obj.getClass()) {
272 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
273 return Objects.equals(context, other.context) && Objects.equals(data, other.data);