Bug 1443: Implemented Lazy deserialization using dynamic proxies
[mdsal.git] / code-generator / binding-data-codec / src / main / java / org / opendaylight / yangtools / binding / data / codec / impl / LazyDataObject.java
1 /*
2  * Copyright (c) 2014 Cisco Systems, Inc. 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 package org.opendaylight.yangtools.binding.data.codec.impl;
9
10 import com.google.common.base.Objects.ToStringHelper;
11 import com.google.common.base.Optional;
12 import com.google.common.base.Preconditions;
13 import com.google.common.collect.ImmutableMap;
14
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.Map;
20 import java.util.Objects;
21 import java.util.concurrent.ConcurrentHashMap;
22
23 import org.opendaylight.yangtools.binding.data.codec.util.AugmentationReader;
24 import org.opendaylight.yangtools.yang.binding.Augmentable;
25 import org.opendaylight.yangtools.yang.binding.Augmentation;
26 import org.opendaylight.yangtools.yang.binding.DataObject;
27 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier.PathArgument;
28 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNode;
29 import org.opendaylight.yangtools.yang.data.api.schema.NormalizedNodeContainer;
30 import org.slf4j.Logger;
31 import org.slf4j.LoggerFactory;
32
33 class LazyDataObject implements InvocationHandler, AugmentationReader {
34
35     private static final Logger LOG = LoggerFactory.getLogger(LazyDataObject.class);
36     private static final String GET_IMPLEMENTED_INTERFACE = "getImplementedInterface";
37     private static final String TO_STRING = "toString";
38     private static final String EQUALS = "equals";
39     private static final String GET_AUGMENTATION = "getAugmentation";
40     private static final String HASHCODE = "hashCode";
41     private static final Object NULL_VALUE = new Object();
42
43     private final ConcurrentHashMap<Method, Object> cachedData = new ConcurrentHashMap<>();
44     private final NormalizedNodeContainer<?, PathArgument, NormalizedNode<?, ?>> data;
45     private final DataObjectCodecContext<?> context;
46
47     private volatile ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> cachedAugmentations = null;
48     private volatile Integer cachedHashcode = null;
49
50     @SuppressWarnings({ "rawtypes", "unchecked" })
51     private LazyDataObject(final DataObjectCodecContext<?> ctx, final NormalizedNodeContainer data) {
52         this.context = Preconditions.checkNotNull(ctx, "Context must not be null");
53         this.data = Preconditions.checkNotNull(data, "Data must not be null");
54     }
55
56     @SuppressWarnings("rawtypes")
57     static DataObject create(final DataObjectCodecContext ctx, final NormalizedNodeContainer<?, ?, ?> data) {
58         Class<?> bindingClass = ctx.bindingClass();
59         return (DataObject) Proxy.newProxyInstance(bindingClass.getClassLoader(), new Class<?>[] { bindingClass },
60                 new LazyDataObject(ctx, data));
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             String name = method.getName();
67             if (GET_IMPLEMENTED_INTERFACE.equals(name)) {
68                 return context.bindingClass();
69             } else if (TO_STRING.equals(name)) {
70                 return bindingToString();
71             } else if (HASHCODE.equals(name)) {
72                 return bindingHashCode();
73             }
74             return getBindingData(method);
75         } else if (GET_AUGMENTATION.equals(method.getName())) {
76             return getAugmentationImpl((Class<?>) args[0]);
77         } else if (EQUALS.equals(method.getName())) {
78             return bindingEquals(args[0]);
79         }
80         throw new UnsupportedOperationException("UNsupported method " + method);
81     }
82
83     private boolean bindingEquals(final Object other) {
84         if (other == null) {
85             return false;
86         }
87         if (!context.bindingClass().isAssignableFrom(other.getClass())) {
88             return false;
89         }
90         try {
91             for (Method m : context.getHashCodeAndEqualsMethods()) {
92                 Object thisValue = getBindingData(m);
93                 Object otherValue = m.invoke(other);
94                 if(!Objects.equals(thisValue, otherValue)) {
95                     return false;
96                 }
97             }
98         } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
99             LOG.warn("Can not determine equality of {} and {}",this,other,e);
100             return false;
101         }
102         return true;
103     }
104
105     private Integer bindingHashCode() {
106         Integer ret = cachedHashcode;
107         if (ret != null) {
108             return ret;
109         }
110
111         final int prime = 31;
112         int result = 1;
113         for (Method m : context.getHashCodeAndEqualsMethods()) {
114             Object value = getBindingData(m);
115             result += prime * result + ((value == null) ? 0 : value.hashCode());
116         }
117         if (Augmentation.class.isAssignableFrom(context.bindingClass())) {
118             result += prime * result + (getAugmentations(this).hashCode());
119         }
120         cachedHashcode = result;
121         return result;
122     }
123
124     private Object getBindingData(final Method method) {
125         Object cached = cachedData.get(method);
126         if (cached == null) {
127             Object readedValue = context.getBindingChildValue(method, data);
128             if (readedValue == null) {
129                 cached = NULL_VALUE;
130             } else {
131                 cached = readedValue;
132             }
133             cachedData.putIfAbsent(method, cached);
134         }
135
136         return cached == NULL_VALUE ? null : cached;
137     }
138
139     @Override
140     public Map<Class<? extends Augmentation<?>>, Augmentation<?>> getAugmentations(final Object obj) {
141         Preconditions.checkArgument(this == Proxy.getInvocationHandler(obj),
142                 "Supplied object is not associated with this proxy handler");
143
144         ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> ret = cachedAugmentations;
145         if (ret == null) {
146             synchronized (this) {
147                 ret = cachedAugmentations;
148                 if (ret == null) {
149                     ret = ImmutableMap.copyOf(context.getAllAugmentationsFrom(data));
150                     cachedAugmentations = ret;
151                 }
152             }
153         }
154
155         return ret;
156     }
157
158     private Object getAugmentationImpl(final Class<?> cls) {
159         final ImmutableMap<Class<? extends Augmentation<?>>, Augmentation<?>> aug = cachedAugmentations;
160         if (aug != null) {
161             return aug.get(cls);
162         }
163
164         final DataContainerCodecContext<?> augCtx = context.getStreamChild(cls);
165         final Optional<NormalizedNode<?, ?>> augData = data.getChild(augCtx.getDomPathArgument());
166         if (augData.isPresent()) {
167             return augCtx.dataFromNormalizedNode(augData.get());
168         }
169         return null;
170     }
171
172     public String bindingToString() {
173         ToStringHelper helper = com.google.common.base.Objects.toStringHelper(context.bindingClass());
174
175         for (Method m :context.getHashCodeAndEqualsMethods()) {
176             helper.add(m.getName(), getBindingData(m));
177         }
178         if (Augmentable.class.isAssignableFrom(context.bindingClass())) {
179             helper.add("augmentations", getAugmentations(this));
180         }
181         return helper.toString();
182     }
183
184     @Override
185     public int hashCode() {
186         final int prime = 31;
187         int result = 1;
188         result = prime * result + context.hashCode();
189         result = prime * result + data.hashCode();
190         return result;
191     }
192
193     @Override
194     public boolean equals(final Object obj) {
195         if (this == obj) {
196             return true;
197         }
198         if (obj == null) {
199             return false;
200         }
201         if (getClass() != obj.getClass()) {
202             return false;
203         }
204         LazyDataObject other = (LazyDataObject) obj;
205         if (context == null) {
206             if (other.context != null) {
207                 return false;
208             }
209         } else if (!context.equals(other.context)) {
210             return false;
211         }
212         if (data == null) {
213             if (other.data != null) {
214                 return false;
215             }
216         } else if (!data.equals(other.data)) {
217             return false;
218         }
219         return true;
220     }
221
222 }