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.mdsal.binding.spec.naming.BindingMapping.AUGMENTABLE_AUGMENTATION_NAME;
11 import static org.opendaylight.mdsal.binding.spec.naming.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 java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
27 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
28 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
29 import org.opendaylight.yangtools.yang.binding.Augmentable;
30 import org.opendaylight.yangtools.yang.binding.Augmentation;
31 import org.opendaylight.yangtools.yang.binding.DataObject;
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";
45 private static final Object NULL_VALUE = new Object();
47 private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
48 private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
49 private final DataObjectCodecContext<D,?> context;
51 @SuppressWarnings("rawtypes")
52 private static final AtomicReferenceFieldUpdater<LazyDataObject, ImmutableMap> CACHED_AUGMENTATIONS_UPDATER =
53 AtomicReferenceFieldUpdater.newUpdater(LazyDataObject.class, ImmutableMap.class, "cachedAugmentations");
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 if (method.getParameterTypes().length == 0) {
66 final String name = method.getName();
67 if (DATA_CONTAINER_GET_IMPLEMENTED_INTERFACE_NAME.equals(name)) {
68 return context.getBindingClass();
69 } else if (TO_STRING.equals(name)) {
70 return bindingToString();
71 } else if (HASHCODE.equals(name)) {
72 return bindingHashCode();
73 } else if (AUGMENTATIONS.equals(name)) {
74 return getAugmentationsImpl();
76 return getBindingData(method);
77 } else if (AUGMENTABLE_AUGMENTATION_NAME.equals(method.getName())) {
78 return getAugmentationImpl((Class<?>) args[0]);
79 } else if (EQUALS.equals(method.getName())) {
80 return bindingEquals(args[0]);
82 throw new UnsupportedOperationException("Unsupported method " + method);
85 private boolean bindingEquals(final Object other) {
89 final Class<D> bindingClass = context.getBindingClass();
90 if (!bindingClass.isAssignableFrom(other.getClass())) {
94 for (final Method m : context.getHashCodeAndEqualsMethods()) {
95 final Object thisValue = getBindingData(m);
96 final Object otherValue = m.invoke(other);
98 * added for valid byte array comparison, when list key type is binary
99 * deepEquals is not used since it does excessive amount of instanceof calls.
101 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
102 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
105 } else if (!Objects.equals(thisValue, otherValue)) {
110 if (Augmentable.class.isAssignableFrom(bindingClass)) {
111 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
115 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
116 LOG.warn("Can not determine equality of {} and {}", this, other, e);
122 private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
123 if (dataObject instanceof AugmentationReader) {
124 return ((AugmentationReader) dataObject).getAugmentations(dataObject);
125 } else if (dataObject instanceof Augmentable<?>) {
126 return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
129 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
132 private Integer bindingHashCode() {
133 final Integer ret = cachedHashcode;
138 final int prime = 31;
140 for (final Method m : context.getHashCodeAndEqualsMethods()) {
141 final Object value = getBindingData(m);
142 result = prime * result + Objects.hashCode(value);
144 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
145 result = prime * result + getAugmentationsImpl().hashCode();
147 cachedHashcode = result;
151 private Object getBindingData(final Method method) {
152 Object cached = cachedData.get(method);
153 if (cached == null) {
154 final Object readedValue = context.getBindingChildValue(method, data);
155 if (readedValue == null) {
158 cached = readedValue;
160 cachedData.putIfAbsent(method, cached);
163 return cached == NULL_VALUE ? null : cached;
166 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
167 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> local = cachedAugmentations;
172 local = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
173 return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
177 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
178 Preconditions.checkArgument(this == Proxy.getInvocationHandler(obj),
179 "Supplied object is not associated with this proxy handler");
181 return getAugmentationsImpl();
184 private Object getAugmentationImpl(final Class<?> cls) {
185 Preconditions.checkNotNull(cls, "Supplied augmentation must not be null.");
187 final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
192 @SuppressWarnings({"unchecked","rawtypes"})
193 final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild((Class) cls);
194 if (optAugCtx.isPresent()) {
195 final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
196 // Due to binding specification not representing grouping instantiations we can end up having the same
197 // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
198 // are still represented by distinct binding classes and therefore we need to make sure the result matches
199 // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
200 // ClassCastException.
201 if (cls.isAssignableFrom(augCtx.getBindingClass())) {
202 final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
203 if (augData.isPresent()) {
204 return augCtx.deserialize(augData.get());
211 public String bindingToString() {
212 final Class<D> bindingClass = context.getBindingClass();
213 final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
215 for (final Method m : context.getHashCodeAndEqualsMethods()) {
216 helper.add(m.getName(), getBindingData(m));
218 if (Augmentable.class.isAssignableFrom(bindingClass)) {
219 helper.add("augmentations", getAugmentationsImpl());
221 return helper.toString();
225 public int hashCode() {
226 final int prime = 31;
228 result = prime * result + context.hashCode();
229 result = prime * result + data.hashCode();
234 public boolean equals(final Object obj) {
241 if (getClass() != obj.getClass()) {
244 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
245 return Objects.equals(context, other.context) && Objects.equals(data, other.data);