Switch to Objects.requireNonNull
[mdsal.git] / binding2 / mdsal-binding2-dom-codec / src / main / java / org / opendaylight / mdsal / binding / javav2 / dom / codec / impl / context / base / LazyTreeNode.java
1 /*
2  * Copyright (c) 2017 Pantheon Technologies s.r.o. and others.  All rights reserved.
3  *
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
7  */
8
9 package org.opendaylight.mdsal.binding.javav2.dom.codec.impl.context.base;
10
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.annotations.Beta;
14 import com.google.common.base.MoreObjects;
15 import com.google.common.base.MoreObjects.ToStringHelper;
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;
23 import java.util.Map;
24 import java.util.Objects;
25 import java.util.Optional;
26 import java.util.concurrent.ConcurrentHashMap;
27 import org.opendaylight.mdsal.binding.javav2.dom.codec.api.AugmentationReader;
28 import org.opendaylight.mdsal.binding.javav2.runtime.reflection.BindingReflections;
29 import org.opendaylight.mdsal.binding.javav2.spec.base.TreeNode;
30 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentable;
31 import org.opendaylight.mdsal.binding.javav2.spec.structural.Augmentation;
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;
37
38 @Beta
39 class LazyTreeNode<D extends TreeNode> implements InvocationHandler, AugmentationReader {
40
41     private static final Logger LOG = LoggerFactory.getLogger(LazyTreeNode.class);
42     private static final String GET_IMPLEMENTED_INTERFACE = "implementedInterface";
43     private static final String TO_STRING = "toString";
44     private static final String EQUALS = "equals";
45     private static final String GET_AUGMENTATION = "getAugmentation";
46     private static final String HASHCODE = "hashCode";
47     private static final String AUGMENTATIONS = "augmentations";
48     private static final Object NULL_VALUE = new Object();
49
50     private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
51     private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
52     private final TreeNodeCodecContext<D,?> context;
53
54     private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
55     private volatile Integer cachedHashcode = null;
56
57     @SuppressWarnings({ "rawtypes", "unchecked" })
58     LazyTreeNode(final TreeNodeCodecContext<D,?> ctx, final NormalizedNodeContainer data) {
59         this.context = requireNonNull(ctx, "Context must not be null");
60         this.data = requireNonNull(data, "Data must not be null");
61     }
62
63     @Override
64     public Object invoke(final Object proxy, final Method method, final Object[] args) throws Throwable {
65         if (method.getParameterTypes().length == 0) {
66             final String name = method.getName();
67             if (GET_IMPLEMENTED_INTERFACE.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();
75             }
76             return getBindingData(method);
77         } else if (GET_AUGMENTATION.equals(method.getName())) {
78             return getAugmentationImpl((Class<?>) args[0]);
79         } else if (EQUALS.equals(method.getName())) {
80             return bindingEquals(args[0]);
81         }
82         throw new UnsupportedOperationException("Unsupported method " + method);
83     }
84
85     private boolean bindingEquals(final Object other) {
86         if (other == null) {
87             return false;
88         }
89         if (!context.getBindingClass().isAssignableFrom(other.getClass())) {
90             return false;
91         }
92         try {
93             for (final Method m : context.getHashCodeAndEqualsMethods()) {
94                 final Object thisValue = getBindingData(m);
95                 final Object otherValue = m.invoke(other);
96                 /*
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.
99                  */
100                 if (thisValue instanceof byte[] && otherValue instanceof byte[]) {
101                     if (!Arrays.equals((byte[]) thisValue, (byte[]) otherValue)) {
102                         return false;
103                     }
104                 } else if (!Objects.equals(thisValue, otherValue)) {
105                     return false;
106                 }
107             }
108
109             if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
110                 if (!getAugmentationsImpl().equals(getAllAugmentations(other))) {
111                     return false;
112                 }
113             }
114         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
115             LOG.warn("Can not determine equality of {} and {}", this, other, e);
116             return false;
117         }
118         return true;
119     }
120
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);
126         }
127
128         throw new IllegalArgumentException("Unable to get all augmentations from " + dataObject);
129     }
130
131     private Integer bindingHashCode() {
132         final Integer ret = cachedHashcode;
133         if (ret != null) {
134             return ret;
135         }
136
137         final int prime = 31;
138         int result = 1;
139         for (final Method m : context.getHashCodeAndEqualsMethods()) {
140             final Object value = getBindingData(m);
141             result = prime * result + Objects.hashCode(value);
142         }
143         if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
144             result = prime * result + getAugmentationsImpl().hashCode();
145         }
146         cachedHashcode = result;
147         return result;
148     }
149
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) {
155                 cached = NULL_VALUE;
156             } else {
157                 cached = readedValue;
158             }
159             cachedData.putIfAbsent(method, cached);
160         }
161
162         return cached == NULL_VALUE ? null : cached;
163     }
164
165     private Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentationsImpl() {
166         ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> ret = cachedAugmentations;
167         if (ret == null) {
168             synchronized (this) {
169                 ret = cachedAugmentations;
170                 if (ret == null) {
171                     ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
172                     cachedAugmentations = ret;
173                 }
174             }
175         }
176
177         return ret;
178     }
179
180     @Override
181     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
182         Preconditions.checkArgument(this == Proxy.getInvocationHandler(obj),
183                 "Supplied object is not associated with this proxy handler");
184
185         return getAugmentationsImpl();
186     }
187
188     private Object getAugmentationImpl(final Class<?> cls) {
189         final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
190         if (aug != null) {
191             return aug.get(cls);
192         }
193         requireNonNull(cls,"Supplied augmentation must not be null.");
194
195         @SuppressWarnings({"unchecked","rawtypes"})
196         final Optional<DataContainerCodecContext<?,?>> augCtx = context.possibleStreamChild((Class) cls);
197         if (augCtx.isPresent()) {
198             final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.get().getDomPathArgument());
199             if (augData.isPresent()) {
200                 return augCtx.get().deserialize(augData.get());
201             }
202         }
203         return null;
204     }
205
206     public String bindingToString() {
207         final ToStringHelper helper = MoreObjects.toStringHelper(context.getBindingClass()).omitNullValues();
208
209         for (final Method m :context.getHashCodeAndEqualsMethods()) {
210             helper.add(m.getName(), getBindingData(m));
211         }
212         if (Augmentable.class.isAssignableFrom(context.getBindingClass())) {
213             helper.add("augmentations", getAugmentationsImpl());
214         }
215         return helper.toString();
216     }
217
218     @Override
219     public int hashCode() {
220         return Objects.hash(this.context, this.data);
221     }
222
223     @Override
224     public boolean equals(final Object obj) {
225         if (this == obj) {
226             return true;
227         }
228         if (obj == null) {
229             return false;
230         }
231         if (getClass() != obj.getClass()) {
232             return false;
233         }
234         final LazyTreeNode<?> other = (LazyTreeNode<?>) obj;
235         return Objects.equals(context, other.context) && Objects.equals(data, other.data);
236     }
237 }