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.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14 import java.lang.reflect.InvocationHandler;
15 import java.lang.reflect.InvocationTargetException;
16 import java.lang.reflect.Method;
17 import java.lang.reflect.Proxy;
18 import java.util.Arrays;
20 import java.util.Objects;
21 import java.util.Optional;
22 import java.util.concurrent.ConcurrentHashMap;
23 import org.opendaylight.mdsal.binding.dom.codec.util.AugmentationReader;
24 import org.opendaylight.mdsal.binding.spec.naming.BindingMapping;
25 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
26 import org.opendaylight.yangtools.yang.binding.Augmentable;
27 import org.opendaylight.yangtools.yang.binding.Augmentation;
28 import org.opendaylight.yangtools.yang.binding.DataObject;
29 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
30 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
31 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
32 import org.slf4j.Logger;
33 import org.slf4j.LoggerFactory;
35 class LazyDataObject<D extends DataObject> implements InvocationHandler, AugmentationReader {
37 private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
38 private static final String GET_IMPLEMENTED_INTERFACE = "getImplementedInterface";
39 private static final String TO_STRING = "toString";
40 private static final String EQUALS = "equals";
41 private static final String HASHCODE = "hashCode";
42 private static final String AUGMENTATIONS = "augmentations";
43 private static final Object NULL_VALUE = new Object();
45 private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
46 private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
47 private final DataObjectCodecContext<D,?> context;
49 private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
50 private volatile Integer cachedHashcode = null;
52 @SuppressWarnings({ "rawtypes", "unchecked" })
53 LazyDataObject(final DataObjectCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
54 this.context = Preconditions.checkNotNull(ctx, "Context must not be null");
55 this.data = Preconditions.checkNotNull(data, "Data must not be null");
59 public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
60 if (method.getParameterTypes().length == 0) {
61 final String name = method.getName();
62 if (GET_IMPLEMENTED_INTERFACE.equals(name)) {
63 return context.getBindingClass();
64 } else if (TO_STRING.equals(name)) {
65 return bindingToString();
66 } else if (HASHCODE.equals(name)) {
67 return bindingHashCode();
68 } else if (AUGMENTATIONS.equals(name)) {
69 return getAugmentationsImpl();
71 return getBindingData(method);
72 } else if (BindingMapping.AUGMENTABLE_AUGMENTATION_NAME.equals(method.getName())) {
73 return getAugmentationImpl((Class<?>) args[0]);
74 } else if (EQUALS.equals(method.getName())) {
75 return bindingEquals(args[0]);
77 throw new UnsupportedOperationException("Unsupported method " + method);
80 private boolean bindingEquals(final Object other) {
84 if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
88 for (final Method m : context.getHashCodeAndEqualsMethods()) {
89 final Object thisValue = getBindingData(m);
90 final Object otherValue = m.invoke(other);
92 * added for valid byte array comparison, when list key type is binary
93 * deepEquals is not used since it does excessive amount of instanceof calls.
95 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
96 if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
99 } else if (!Objects.equals(thisValue, otherValue)) {
104 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
105 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
109 } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
110 LOG.warn("Can not determine equality of {} and {}", this, other, e);
116 private static Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAllAugmentations(final Object dataObject) {
117 if (dataObject instanceof AugmentationReader) {
118 return ((AugmentationReader) dataObject).getAugmentations(dataObject);
119 } else if (dataObject instanceof Augmentable<?>) {
120 return BindingReflections.getAugmentations((Augmentable<?>) dataObject);
123 throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
126 private Integer bindingHashCode() {
127 final Integer ret = cachedHashcode;
132 final int prime = 31;
134 for (final Method m : context.getHashCodeAndEqualsMethods()) {
135 final Object value = getBindingData(m);
136 result = prime * result + Objects.hashCode(value);
138 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
139 result = prime * result + getAugmentationsImpl().hashCode();
141 cachedHashcode = result;
145 private Object getBindingData(final Method method) {
146 Object cached = cachedData.get(method);
147 if (cached == null) {
148 final Object readedValue = context.getBindingChildValue(method, data);
149 if (readedValue == null) {
152 cached = readedValue;
154 cachedData.putIfAbsent(method, cached);
157 return cached == NULL_VALUE ? null : cached;
160 private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
161 ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> ret = cachedAugmentations;
163 synchronized (this) {
164 ret = cachedAugmentations;
166 ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
167 cachedAugmentations = ret;
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 ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
213 for (final Method m : context.getHashCodeAndEqualsMethods()) {
214 helper.add(m.getName(), getBindingData(m));
216 if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
217 helper.add("augmentations", getAugmentationsImpl());
219 return helper.toString();
223 public int hashCode() {
224 final int prime = 31;
226 result = prime * result + context.hashCode();
227 result = prime * result + data.hashCode();
232 public boolean equals(final Object obj) {
239 if (getClass() != obj.getClass()) {
242 final LazyDataObject<?> other = (LazyDataObject<?>) obj;
243 return Objects.equals(context, other.context) && Objects.equals(data, other.data);