Do not retain java.lang.reflect.Method in ValueNodeCodecContext
[mdsal.git] / binding / mdsal-binding-dom-codec / src / main / java / org / opendaylight / mdsal / binding / dom / codec / impl / BindingCodecContext.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.mdsal.binding.dom.codec.impl;
9
10 import static com.google.common.base.Preconditions.checkArgument;
11 import static com.google.common.base.Preconditions.checkState;
12 import static com.google.common.base.Verify.verify;
13 import static java.util.Objects.requireNonNull;
14
15 import com.google.common.cache.CacheBuilder;
16 import com.google.common.cache.CacheLoader;
17 import com.google.common.cache.LoadingCache;
18 import com.google.common.collect.ImmutableMap;
19 import java.io.IOException;
20 import java.lang.reflect.Field;
21 import java.lang.reflect.Method;
22 import java.lang.reflect.ParameterizedType;
23 import java.lang.reflect.Type;
24 import java.util.AbstractMap.SimpleEntry;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.LinkedList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Map.Entry;
31 import java.util.Optional;
32 import java.util.concurrent.Callable;
33 import java.util.concurrent.ExecutionException;
34 import org.eclipse.jdt.annotation.NonNull;
35 import org.eclipse.jdt.annotation.Nullable;
36 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTree;
37 import org.opendaylight.mdsal.binding.dom.codec.api.BindingCodecTreeNode;
38 import org.opendaylight.mdsal.binding.dom.codec.api.BindingDataObjectCodecTreeNode;
39 import org.opendaylight.mdsal.binding.dom.codec.impl.NodeCodecContext.CodecContextFactory;
40 import org.opendaylight.mdsal.binding.dom.codec.loader.CodecClassLoader;
41 import org.opendaylight.mdsal.binding.dom.codec.util.BindingSchemaMapping;
42 import org.opendaylight.mdsal.binding.generator.util.BindingRuntimeContext;
43 import org.opendaylight.mdsal.binding.model.api.GeneratedType;
44 import org.opendaylight.mdsal.binding.spec.reflect.BindingReflections;
45 import org.opendaylight.yangtools.concepts.Codec;
46 import org.opendaylight.yangtools.concepts.Delegator;
47 import org.opendaylight.yangtools.concepts.Immutable;
48 import org.opendaylight.yangtools.util.ClassLoaderUtils;
49 import org.opendaylight.yangtools.yang.binding.Action;
50 import org.opendaylight.yangtools.yang.binding.BindingStreamEventWriter;
51 import org.opendaylight.yangtools.yang.binding.DataContainer;
52 import org.opendaylight.yangtools.yang.binding.DataObject;
53 import org.opendaylight.yangtools.yang.binding.DataObjectSerializer;
54 import org.opendaylight.yangtools.yang.binding.DataObjectSerializerRegistry;
55 import org.opendaylight.yangtools.yang.binding.Identifiable;
56 import org.opendaylight.yangtools.yang.binding.Identifier;
57 import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
58 import org.opendaylight.yangtools.yang.binding.Notification;
59 import org.opendaylight.yangtools.yang.binding.OpaqueObject;
60 import org.opendaylight.yangtools.yang.common.QName;
61 import org.opendaylight.yangtools.yang.data.api.YangInstanceIdentifier;
62 import org.opendaylight.yangtools.yang.data.api.schema.stream.NormalizedNodeStreamWriter;
63 import org.opendaylight.yangtools.yang.model.api.AnyXmlSchemaNode;
64 import org.opendaylight.yangtools.yang.model.api.DataNodeContainer;
65 import org.opendaylight.yangtools.yang.model.api.DataSchemaNode;
66 import org.opendaylight.yangtools.yang.model.api.DocumentedNode.WithStatus;
67 import org.opendaylight.yangtools.yang.model.api.LeafListSchemaNode;
68 import org.opendaylight.yangtools.yang.model.api.LeafSchemaNode;
69 import org.opendaylight.yangtools.yang.model.api.ListSchemaNode;
70 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
71 import org.opendaylight.yangtools.yang.model.api.TypeDefinition;
72 import org.opendaylight.yangtools.yang.model.api.TypedDataSchemaNode;
73 import org.opendaylight.yangtools.yang.model.api.type.IdentityrefTypeDefinition;
74 import org.opendaylight.yangtools.yang.model.api.type.InstanceIdentifierTypeDefinition;
75 import org.opendaylight.yangtools.yang.model.api.type.LeafrefTypeDefinition;
76 import org.opendaylight.yangtools.yang.model.api.type.UnionTypeDefinition;
77 import org.slf4j.Logger;
78 import org.slf4j.LoggerFactory;
79
80 final class BindingCodecContext implements CodecContextFactory, BindingCodecTree, DataObjectSerializerRegistry,
81         Immutable {
82     private final class DataObjectSerializerProxy implements DataObjectSerializer, Delegator<DataObjectStreamer<?>> {
83         private final @NonNull DataObjectStreamer<?> delegate;
84
85         DataObjectSerializerProxy(final DataObjectStreamer<?> delegate) {
86             this.delegate = requireNonNull(delegate);
87         }
88
89         @Override
90         public DataObjectStreamer<?> getDelegate() {
91             return delegate;
92         }
93
94         @Override
95         public void serialize(final DataObject obj, final BindingStreamEventWriter stream) throws IOException {
96             delegate.serialize(BindingCodecContext.this, obj, stream);
97         }
98     }
99
100     private static final Logger LOG = LoggerFactory.getLogger(BindingCodecContext.class);
101
102     private final LoadingCache<Class<?>, DataObjectStreamer<?>> streamers = CacheBuilder.newBuilder().build(
103         new CacheLoader<Class<?>, DataObjectStreamer<?>>() {
104             @Override
105             public DataObjectStreamer<?> load(final Class<?> key) throws ReflectiveOperationException {
106                 final Class<?> streamer = DataObjectStreamerGenerator.generateStreamer(loader, BindingCodecContext.this,
107                     key);
108                 final Field instance = streamer.getDeclaredField(DataObjectStreamerGenerator.INSTANCE_FIELD);
109                 return (DataObjectStreamer<?>) instance.get(null);
110             }
111         });
112     private final LoadingCache<Class<?>, DataObjectSerializer> serializers = CacheBuilder.newBuilder().build(
113         new CacheLoader<Class<?>, DataObjectSerializer>() {
114             @Override
115             public DataObjectSerializer load(final Class<?> key) throws ExecutionException {
116                 return new DataObjectSerializerProxy(streamers.get(key));
117             }
118         });
119
120     private final @NonNull CodecClassLoader loader = CodecClassLoader.create();
121     private final InstanceIdentifierCodec instanceIdentifierCodec;
122     private final IdentityCodec identityCodec;
123     private final BindingNormalizedNodeCodecRegistry registry;
124     private final BindingRuntimeContext context;
125     private final SchemaRootCodecContext<?> root;
126
127     BindingCodecContext(final BindingRuntimeContext context, final BindingNormalizedNodeCodecRegistry registry) {
128         this.context = requireNonNull(context, "Binding Runtime Context is required.");
129         this.root = SchemaRootCodecContext.create(this);
130         this.identityCodec = new IdentityCodec(context);
131         this.instanceIdentifierCodec = new InstanceIdentifierCodec(this);
132         this.registry = requireNonNull(registry);
133     }
134
135     @Override
136     public BindingRuntimeContext getRuntimeContext() {
137         return context;
138     }
139
140     @Override
141     public CodecClassLoader getLoader() {
142         return loader;
143     }
144
145     InstanceIdentifierCodec getInstanceIdentifierCodec() {
146         return instanceIdentifierCodec;
147     }
148
149     IdentityCodec getIdentityCodec() {
150         return identityCodec;
151     }
152
153     @SuppressWarnings({"rawtypes", "unchecked"})
154     @Override
155     public DataObjectSerializer getEventStreamSerializer(final Class<?> type) {
156         return registry.getSerializer((Class) type);
157     }
158
159     @Override
160     public DataObjectStreamer<?> getDataObjectSerializer(final Class<?> type) {
161         return streamers.getUnchecked(type);
162     }
163
164     @Override
165     public DataObjectSerializer getSerializer(final Class<? extends DataObject> type) {
166         return serializers.getUnchecked(type);
167     }
168
169     public Entry<YangInstanceIdentifier, BindingStreamEventWriter> newWriter(final InstanceIdentifier<?> path,
170             final NormalizedNodeStreamWriter domWriter) {
171         final List<YangInstanceIdentifier.PathArgument> yangArgs = new LinkedList<>();
172         final DataContainerCodecContext<?,?> codecContext = getCodecContextNode(path, yangArgs);
173         return new SimpleEntry<>(YangInstanceIdentifier.create(yangArgs), codecContext.createWriter(domWriter));
174     }
175
176     public BindingStreamEventWriter newWriterWithoutIdentifier(final InstanceIdentifier<?> path,
177             final NormalizedNodeStreamWriter domWriter) {
178         return getCodecContextNode(path, null).createWriter(domWriter);
179     }
180
181     BindingStreamEventWriter newRpcWriter(final Class<? extends DataContainer> rpcInputOrOutput,
182             final NormalizedNodeStreamWriter domWriter) {
183         return root.getRpc(rpcInputOrOutput).createWriter(domWriter);
184     }
185
186     BindingStreamEventWriter newNotificationWriter(final Class<? extends Notification> notification,
187             final NormalizedNodeStreamWriter domWriter) {
188         return root.getNotification(notification).createWriter(domWriter);
189     }
190
191     public DataContainerCodecContext<?,?> getCodecContextNode(final InstanceIdentifier<?> binding,
192             final List<YangInstanceIdentifier.PathArgument> builder) {
193         DataContainerCodecContext<?,?> currentNode = root;
194         for (final InstanceIdentifier.PathArgument bindingArg : binding.getPathArguments()) {
195             currentNode = currentNode.bindingPathArgumentChild(bindingArg, builder);
196             checkArgument(currentNode != null, "Supplied Instance Identifier %s is not valid.", binding);
197         }
198         return currentNode;
199     }
200
201     /**
202      * Multi-purpose utility function. Traverse the codec tree, looking for
203      * the appropriate codec for the specified {@link YangInstanceIdentifier}.
204      * As a side-effect, gather all traversed binding {@link InstanceIdentifier.PathArgument}s
205      * into the supplied collection.
206      *
207      * @param dom {@link YangInstanceIdentifier} which is to be translated
208      * @param bindingArguments Collection for traversed path arguments
209      * @return Codec for target node, or @null if the node does not have a
210      *         binding representation (choice, case, leaf).
211      *
212      */
213     @Nullable BindingDataObjectCodecTreeNode<?> getCodecContextNode(final @NonNull YangInstanceIdentifier dom,
214             final @Nullable Collection<InstanceIdentifier.PathArgument> bindingArguments) {
215         NodeCodecContext currentNode = root;
216         ListNodeCodecContext<?> currentList = null;
217
218         for (final YangInstanceIdentifier.PathArgument domArg : dom.getPathArguments()) {
219             checkArgument(currentNode instanceof DataContainerCodecContext,
220                 "Unexpected child of non-container node %s", currentNode);
221             final DataContainerCodecContext<?,?> previous = (DataContainerCodecContext<?, ?>) currentNode;
222             final NodeCodecContext nextNode = previous.yangPathArgumentChild(domArg);
223
224             /*
225              * List representation in YANG Instance Identifier consists of two
226              * arguments: first is list as a whole, second is list as an item so
227              * if it is /list it means list as whole, if it is /list/list - it
228              * is wildcarded and if it is /list/list[key] it is concrete item,
229              * all this variations are expressed in Binding Aware Instance
230              * Identifier as Item or IdentifiableItem
231              */
232             if (currentList != null) {
233                 checkArgument(currentList == nextNode,
234                         "List should be referenced two times in YANG Instance Identifier %s", dom);
235
236                 // We entered list, so now we have all information to emit
237                 // list path using second list argument.
238                 if (bindingArguments != null) {
239                     bindingArguments.add(currentList.getBindingPathArgument(domArg));
240                 }
241                 currentList = null;
242                 currentNode = nextNode;
243             } else if (nextNode instanceof ListNodeCodecContext) {
244                 // We enter list, we do not update current Node yet,
245                 // since we need to verify
246                 currentList = (ListNodeCodecContext<?>) nextNode;
247             } else if (nextNode instanceof ChoiceNodeCodecContext) {
248                 // We do not add path argument for choice, since
249                 // it is not supported by binding instance identifier.
250                 currentNode = nextNode;
251             } else if (nextNode instanceof DataContainerCodecContext) {
252                 if (bindingArguments != null) {
253                     bindingArguments.add(((DataContainerCodecContext<?, ?>) nextNode).getBindingPathArgument(domArg));
254                 }
255                 currentNode = nextNode;
256             } else if (nextNode instanceof ValueNodeCodecContext) {
257                 LOG.debug("Instance identifier referencing a leaf is not representable ({})", dom);
258                 return null;
259             }
260         }
261
262         // Algorithm ended in list as whole representation
263         // we sill need to emit identifier for list
264         if (currentNode instanceof ChoiceNodeCodecContext) {
265             LOG.debug("Instance identifier targeting a choice is not representable ({})", dom);
266             return null;
267         }
268         if (currentNode instanceof CaseNodeCodecContext) {
269             LOG.debug("Instance identifier targeting a case is not representable ({})", dom);
270             return null;
271         }
272
273         if (currentList != null) {
274             if (bindingArguments != null) {
275                 bindingArguments.add(currentList.getBindingPathArgument(null));
276             }
277             return currentList;
278         }
279         if (currentNode != null) {
280             verify(currentNode instanceof BindingDataObjectCodecTreeNode, "Illegal return node %s for identifier %s",
281                 currentNode, dom);
282             return (BindingDataObjectCodecTreeNode<?>) currentNode;
283         }
284         return null;
285     }
286
287     NotificationCodecContext<?> getNotificationContext(final SchemaPath notification) {
288         return root.getNotification(notification);
289     }
290
291     RpcInputCodec<?> getRpcInputCodec(final SchemaPath path) {
292         return root.getRpc(path);
293     }
294
295     ActionCodecContext getActionCodec(final Class<? extends Action<?, ?, ?>> action) {
296         return root.getAction(action);
297     }
298
299     @Override
300     public ImmutableMap<Method, ValueNodeCodecContext> getLeafNodes(final Class<?> parentClass,
301             final DataNodeContainer childSchema) {
302         final Map<String, DataSchemaNode> getterToLeafSchema = new HashMap<>();
303         for (final DataSchemaNode leaf : childSchema.getChildNodes()) {
304             // FIXME: support AnyDataSchemaNode, too
305             if (leaf instanceof TypedDataSchemaNode || leaf instanceof AnyXmlSchemaNode) {
306                 getterToLeafSchema.put(BindingSchemaMapping.getGetterMethodName(leaf), leaf);
307             }
308         }
309         return getLeafNodesUsingReflection(parentClass, getterToLeafSchema);
310     }
311
312     private ImmutableMap<Method, ValueNodeCodecContext> getLeafNodesUsingReflection(
313             final Class<?> parentClass, final Map<String, DataSchemaNode> getterToLeafSchema) {
314         final Map<Method, ValueNodeCodecContext> leaves = new HashMap<>();
315         for (final Method method : parentClass.getMethods()) {
316             if (method.getParameterCount() == 0) {
317                 final DataSchemaNode schema = getterToLeafSchema.get(method.getName());
318
319                 final ValueNodeCodecContext valueNode;
320                 if (schema instanceof LeafSchemaNode) {
321                     final LeafSchemaNode leafSchema = (LeafSchemaNode) schema;
322
323                     final Class<?> valueType = method.getReturnType();
324                     final Codec<Object, Object> codec = getCodec(valueType, leafSchema.getType());
325                     valueNode = LeafNodeCodecContext.of(leafSchema, codec, method.getName(), valueType,
326                         context.getSchemaContext());
327                 } else if (schema instanceof LeafListSchemaNode) {
328                     final Optional<Type> optType = ClassLoaderUtils.getFirstGenericParameter(
329                         method.getGenericReturnType());
330                     checkState(optType.isPresent(), "Failed to find return type for %s", method);
331
332                     final Class<?> valueType;
333                     final Type genericType = optType.get();
334                     if (genericType instanceof Class<?>) {
335                         valueType = (Class<?>) genericType;
336                     } else if (genericType instanceof ParameterizedType) {
337                         valueType = (Class<?>) ((ParameterizedType) genericType).getRawType();
338                     } else {
339                         throw new IllegalStateException("Unexpected return type " + genericType);
340                     }
341
342                     final LeafListSchemaNode leafListSchema = (LeafListSchemaNode) schema;
343                     final Codec<Object, Object> codec = getCodec(valueType, leafListSchema.getType());
344                     valueNode = new LeafSetNodeCodecContext(leafListSchema, codec, method.getName());
345                 } else if (schema instanceof AnyXmlSchemaNode) {
346                     final Class<?> valueType = method.getReturnType();
347                     verify(OpaqueObject.class.isAssignableFrom(valueType), "Illegal value type %s", valueType);
348                     valueNode = new OpaqueNodeCodecContext.AnyXml<>((AnyXmlSchemaNode) schema, method.getName(),
349                             valueType.asSubclass(OpaqueObject.class), loader);
350                 } else {
351                     verify(schema == null, "Unhandled schema %s for method %s", schema, method);
352                     // We do not have schema for leaf, so we will ignore it (e.g. getClass).
353                     continue;
354                 }
355
356                 leaves.put(method, valueNode);
357             }
358         }
359         return ImmutableMap.copyOf(leaves);
360     }
361
362     Codec<Object, Object> getCodec(final Class<?> valueType, final TypeDefinition<?> instantiatedType) {
363         if (Class.class.equals(valueType)) {
364             @SuppressWarnings({ "unchecked", "rawtypes" })
365             final Codec<Object, Object> casted = (Codec) identityCodec;
366             return casted;
367         } else if (InstanceIdentifier.class.equals(valueType)) {
368             @SuppressWarnings({ "unchecked", "rawtypes" })
369             final Codec<Object, Object> casted = (Codec) instanceIdentifierCodec;
370             return casted;
371         } else if (BindingReflections.isBindingClass(valueType)) {
372             return getCodecForBindingClass(valueType, instantiatedType);
373         }
374         return ValueTypeCodec.NOOP_CODEC;
375     }
376
377     @SuppressWarnings("checkstyle:illegalCatch")
378     private Codec<Object, Object> getCodecForBindingClass(final Class<?> valueType, final TypeDefinition<?> typeDef) {
379         if (typeDef instanceof IdentityrefTypeDefinition) {
380             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, identityCodec);
381         } else if (typeDef instanceof InstanceIdentifierTypeDefinition) {
382             return ValueTypeCodec.encapsulatedValueCodecFor(valueType, typeDef, instanceIdentifierCodec);
383         } else if (typeDef instanceof UnionTypeDefinition) {
384             final Callable<UnionTypeCodec> unionLoader = UnionTypeCodec.loader(valueType, (UnionTypeDefinition) typeDef,
385                 this);
386             try {
387                 return unionLoader.call();
388             } catch (final Exception e) {
389                 throw new IllegalStateException("Unable to load codec for " + valueType, e);
390             }
391         } else if (typeDef instanceof LeafrefTypeDefinition) {
392             final Entry<GeneratedType, WithStatus> typeWithSchema = context.getTypeWithSchema(valueType);
393             final WithStatus schema = typeWithSchema.getValue();
394             checkState(schema instanceof TypeDefinition);
395             return getCodec(valueType, (TypeDefinition<?>) schema);
396         }
397         return ValueTypeCodec.getCodecFor(valueType, typeDef);
398     }
399
400     @Override
401     public IdentifiableItemCodec getPathArgumentCodec(final Class<?> listClz, final ListSchemaNode schema) {
402         final Optional<Class<Identifier<?>>> optIdentifier = ClassLoaderUtils.findFirstGenericArgument(listClz,
403                 Identifiable.class);
404         checkState(optIdentifier.isPresent(), "Failed to find identifier for %s", listClz);
405
406         final Class<Identifier<?>> identifier = optIdentifier.get();
407         final Map<QName, ValueContext> valueCtx = new HashMap<>();
408         for (final ValueNodeCodecContext leaf : getLeafNodes(identifier, schema).values()) {
409             final QName name = leaf.getDomPathArgument().getNodeType();
410             valueCtx.put(name, new ValueContext(identifier, leaf));
411         }
412         return IdentifiableItemCodec.of(schema, identifier, listClz, valueCtx);
413     }
414
415     @SuppressWarnings("unchecked")
416     @Override
417     public <T extends DataObject> BindingDataObjectCodecTreeNode<T> getSubtreeCodec(final InstanceIdentifier<T> path) {
418         // TODO Do we need defensive check here?
419         return (BindingDataObjectCodecTreeNode<T>) getCodecContextNode(path, null);
420     }
421
422     @Override
423     public BindingCodecTreeNode getSubtreeCodec(final YangInstanceIdentifier path) {
424         return getCodecContextNode(path, null);
425     }
426
427     @Override
428     public BindingCodecTreeNode getSubtreeCodec(final SchemaPath path) {
429         throw new UnsupportedOperationException("Not implemented yet.");
430     }
431 }