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 com.google.common.base.MoreObjects;
11 import com.google.common.base.MoreObjects.ToStringHelper;
12 import com.google.common.base.Optional;
13 import com.google.common.base.Preconditions;
14 import com.google.common.collect.ImmutableMap;
15 import java.lang.reflect.InvocationHandler;
16 import java.lang.reflect.InvocationTargetException;
17 import java.lang.reflect.Method;
18 import java.lang.reflect.Proxy;
19 import java.util.Arrays;
21 import java.util.Objects;
22 import java.util.concurrent.ConcurrentHashMap;
23 import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;
24 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
25 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
26 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
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.data.api.YangInstanceIdentifier.PathArgument;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
32 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
33 import org.slf4j.Logger;
34 import org.slf4j.LoggerFactory;
36 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
38 private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
39 private static final String GET_IMPLEMENTED_INTERFACE = "getImplementedInterface";
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 @SuppressWarnings("rawtypes")
51 private static final AtomicReferenceFieldUpdater<LazyDataObject, ImmutableMap> CACHED_AUGMENTATIONS_UPDATER =
52 AtomicReferenceFieldUpdater.newUpdater(LazyDataObject.class, ImmutableMap.class, "cachedAugmentations");
53 private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
54 private volatile Integer cachedHashcode = null;
56 @SuppressWarnings({ "rawtypes", "unchecked" })
57 LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
58 this.context = Preconditions.checkNotNull(ctx, "Context must not be null");
59 this.data = Preconditions.checkNotNull(data, "Data must not be null");
63 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
64 if (method.getParameterTypes().length == 0) {
65 final String name = method.getName();
66 if (GET_IMPLEMENTED_INTERFACE.equals(name)) {
67 return context.getBindingClass();
68 } else if (TO_STRING.equals(name)) {
69 return bindingToString();
70 } else if (HASHCODE.equals(name)) {
71 return bindingHashCode();
72 } else if (AUGMENTATIONS.equals(name)) {
73 return getAugmentationsImpl();
75 return getBindingData(method);
76 } else if (BindingMapping.AUGMENTABLE_AUGMENTATION_NAME.equals(method.getName())) {
77 return getAugmentationImpl((Class<?>) args[0]);
78 } else if (EQUALS.equals(method.getName())) {
79 return bindingEquals(args[0]);
81 throw new UnsupportedOperationException("Unsupported method " + method);
84 private boolean bindingEquals(final Object other) {
88 final Class<D> bindingClass = context.getBindingClass();
89 if (!bindingClass.isAssignableFrom(other.getClass())) {
93 for (final Method m : context.getHashCodeAndEqualsMethods()) {
94 final Object thisValue = getBindingData(m);
95 final Object otherValue = m.invoke(other);
97 * added for valid byte array comparison, when list key type is binary
98 * deepEquals is not used since it does excessive amount of instanceof calls.
100 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
101 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
104 } else if (!Objects.equals(thisValue, otherValue)) {
109 if (Augmentable.class.isAssignableFrom(bindingClass)) {
110 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
114 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
115 LOG.warn("Can not determine equality of {} and {}", this, other, e);
121 private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
122 if (dataObject instanceof AugmentationReader) {
123 return ((AugmentationReader) dataObject).getAugmentations(dataObject);
124 } else if (dataObject instanceof Augmentable<?>) {
125 return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
128 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
131 private Integer bindingHashCode() {
132 final Integer ret = cachedHashcode;
137 final int prime = 31;
139 for (final Method m : context.getHashCodeAndEqualsMethods()) {
140 final Object value = getBindingData(m);
141 result = prime * result + Objects.hashCode(value);
143 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
144 result = prime * result + getAugmentationsImpl().hashCode();
146 cachedHashcode = result;
150 private Object getBindingData(final Method method) {
151 Object cached = cachedData.get(method);
152 if (cached == null) {
153 final Object readedValue = context.getBindingChildValue(method, data);
154 if (readedValue == null) {
157 cached = readedValue;
159 cachedData.putIfAbsent(method, cached);
162 return cached == NULL_VALUE ? null : cached;
165 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
166 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> local = cachedAugmentations;
171 local = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
172 return CACHED_AUGMENTATIONS_UPDATER.compareAndSet(this, null, local) ? local : cachedAugmentations;
176 public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
177 Preconditions.checkArgument(this == Proxy.getInvocationHandler(obj),
178 "Supplied object is not associated with this proxy handler");
180 return getAugmentationsImpl();
183 private Object getAugmentationImpl(final Class<?> cls) {
184 Preconditions.checkNotNull(cls, "Supplied augmentation must not be null.");
186 final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
191 @SuppressWarnings({"unchecked","rawtypes"})
192 final Optional<DataContainerCodecContext<?, ?>> optAugCtx = context.possibleStreamChild((Class) cls);
193 if (optAugCtx.isPresent()) {
194 final DataContainerCodecContext<?, ?> augCtx = optAugCtx.get();
195 // Due to binding specification not representing grouping instantiations we can end up having the same
196 // augmentation applied to a grouping multiple times. While these augmentations have the same shape, they
197 // are still represented by distinct binding classes and therefore we need to make sure the result matches
198 // the augmentation the user is requesting -- otherwise a strict receiver would end up with a cryptic
199 // ClassCastException.
200 if (cls.isAssignableFrom(augCtx.getBindingClass())) {
201 final java.util.Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
202 if (augData.isPresent()) {
203 return augCtx.deserialize(augData.get());
210 public String bindingToString() {
211 final Class<D> bindingClass = context.getBindingClass();
212 final ToStringHelper helper = MoreObjects.toStringHelper(bindingClass).omitNullValues();
214 for (final Method m : context.getHashCodeAndEqualsMethods()) {
215 helper.add(m.getName(), getBindingData(m));
217 if (Augmentable.class.isAssignableFrom(bindingClass)) {
218 helper.add("augmentations", getAugmentationsImpl());
220 return helper.toString();
224 public int hashCode() {
225 final int prime = 31;
227 result = prime * result + context.hashCode();
228 result = prime * result + data.hashCode();
233 public boolean equals(final Object obj) {
240 if (getClass() != obj.getClass()) {
243 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
244 return Objects.equals(context, other.context) && Objects.equals(data, other.data);