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